import { useCallApi } from '@/hooks';
import { useManageWalletRuleContext } from '../hooks/useManageWalletRuleContext';
import { Alert, useDataGrid } from '@/components';
import React, { useCallback, useEffect, useState } from 'react';
import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { NumericFormat } from 'react-number-format';
import { doSaveLogActivity } from '@/actions/GlobalActions';

interface GroupProps {
  ID: string;
  is_bank: string;
  name: string;
  status: string;
}

interface WalletProps {
  ID: string;
  name: string;
  id_currency: string;
  status: string;
}

const API_URL_WALLET = apiConfig.service_wallet;

const EditDialog = () => {
  const { showEditDialog, handleEditDialog, selectedWalletRule } = useManageWalletRuleContext();
  const { GetData, PutData } = useCallApi();
  const { reload } = useDataGrid();
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState: {
    id_wallet: string;
    id_group: string;
    max_transaction_per_day: string | number | null;
    balance_minimum: string | number | null;
    balance_maximum: string | number | null;
    credit_limit: string | number | null;
    monthly_limit: string | number | null;
    status: string;
  } = {
    id_wallet: '',
    id_group: '',
    max_transaction_per_day: null,
    balance_minimum: null,
    balance_maximum: null,
    credit_limit: null,
    monthly_limit: null,
    status: ''
  };
  const [formField, setFormField] = useState(initialState);
  const [groups, setGroups] = useState<GroupProps[]>([]);
  const [wallets, setWallets] = useState<WalletProps[]>([]);

  const resetForm = () => {
    setFormField(initialState);
    setAlert({ show: false, message: '' });
  };

  const doUpdateWalletRule = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();

      const response = await PutData(
        `${API_URL_WALLET}/dashboard/wallet_rule/${selectedWalletRule?.ID}`,
        formField
      );

      if (response?.status) {
        handleEditDialog(false, null);
        toast.success('Success Update Wallet Rule');
        reload();

        const createActivity = {
          module: 'Manage Wallet Rule',
          description: `Edit Wallet Rule => ${selectedWalletRule?.ID}`,
          action: 'U'
        };

        doSaveLogActivity(createActivity);
      } else {
        toast.error('Failed Update Wallet Rule');
        setAlert({ show: true, message: 'Failed Update Wallet Rule' });
      }
    },
    [formField]
  );

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (formField.id_group.trim() === '' || formField.status.trim() === '') {
      setAlert({ show: true, message: 'Please fill in all required fields.' });
      return;
    }

    // console.log(formField);
    doUpdateWalletRule(e);
    setAlert({ show: false, message: '' });
  };

  const getGroupLists = async (sorting: any) => {
    try {
      const response = await GetData(`${API_URL_WALLET}/dashboard/group`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });

      // console.log('GROUPS: ', response?.data);
      setGroups(response?.data.list);
    } catch (error) {
      console.error('Error fetching groups', error);
    }
  };

  const getWalletLists = async (sorting: any) => {
    try {
      const response = await GetData(`${API_URL_WALLET}/dashboard/wallet`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });

      // console.log('WALLET: ', response?.data);
      setWallets(response?.data.list);
    } catch (error) {
      console.error('Error fetching wallet', error);
    }
  };

  const doFetchData = useCallback(async (id: string) => {
    const response = await GetData(`${API_URL_WALLET}/dashboard/wallet_rule/${id}`, { id });

    console.log(response);
    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        id_wallet: response?.data.id_wallet,
        id_group: response?.data.id_group,
        max_transaction_per_day: response?.data.max_transaction_per_day,
        balance_minimum: response?.data.balance_minimum,
        balance_maximum: response?.data.balance_maximum,
        credit_limit: response?.data.credit_limit,
        monthly_limit: response?.data.monthly_limit,
        status: response?.data.status
      }));
    }
  }, []);

  useEffect(() => {
    getWalletLists([{ id: 'name', desc: false }]);
    getGroupLists([{ id: 'name', desc: false }]);
  }, []);

  useEffect(() => {
    if (showEditDialog === false) {
      resetForm();
    }
  }, [showEditDialog]);

  useEffect(() => {
    if (selectedWalletRule) {
      setFormField((prev) => ({
        ...prev,
        id_wallet: selectedWalletRule?.id_wallet,
        id_group: selectedWalletRule?.id_group,
        max_transaction_per_day: selectedWalletRule?.max_transaction_per_day,
        balance_minimum: selectedWalletRule?.balance_minimum,
        balance_maximum: selectedWalletRule?.balance_maximum,
        credit_limit: selectedWalletRule?.credit_limit,
        monthly_limit: selectedWalletRule?.monthly_limit,
        status: selectedWalletRule?.status
      }));
    }
  }, [selectedWalletRule]);
  // console.log(selectedWalletRule);
  return (
    <Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Wallet Rule - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody className="scrollable">
          <div className="flex flex-col">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}

            <form onSubmit={handleSubmit}>
              <div className="card-body grid gap-5">
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Wallet<span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.id_wallet}
                      onValueChange={(value) => setFormField({ ...formField, id_wallet: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Wallet Type" />
                      </SelectTrigger>
                      <SelectContent>
                        {wallets.map((wallet) => (
                          <SelectItem key={wallet.ID} value={wallet.ID}>
                            {wallet.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Group<span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.id_group}
                      onValueChange={(value) => setFormField({ ...formField, id_group: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Group Type" />
                      </SelectTrigger>
                      <SelectContent>
                        {groups.map((group) => (
                          <SelectItem key={group.ID} value={group.ID}>
                            {group.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Max Transaction Per Day<span className="text-red-500">*</span>
                    </label>
                    <NumericFormat
                      className="input"
                      value={formField.max_transaction_per_day ?? ''}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          max_transaction_per_day:
                            values.floatValue !== undefined ? values.floatValue : ''
                        }));
                      }}
                      placeholder="Enter Max Transaction Per Day"
                    />
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Balance Minimum<span className="text-red-500">*</span>
                    </label>
                    <NumericFormat
                      className="input"
                      value={formField.balance_minimum ?? ''}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          balance_minimum: values.floatValue !== undefined ? values.floatValue : ''
                        }));
                      }}
                      placeholder="Enter Balance Minimum"
                    />
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Balance Maximum<span className="text-red-500">*</span>
                    </label>
                    <NumericFormat
                      className="input"
                      value={formField.balance_maximum ?? ''}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          balance_maximum: values.floatValue !== undefined ? values.floatValue : ''
                        }));
                      }}
                      placeholder="Enter Balance Maximum"
                    />
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Credit Limit<span className="text-red-500">*</span>
                    </label>
                    <NumericFormat
                      className="input"
                      value={formField.credit_limit ?? ''}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          credit_limit: values.floatValue !== undefined ? values.floatValue : ''
                        }));
                      }}
                      placeholder="Enter Credit Limit"
                    />
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Monthly Limit<span className="text-red-500">*</span>
                    </label>
                    <NumericFormat
                      className="input"
                      value={formField.monthly_limit ?? ''}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          monthly_limit: values.floatValue !== undefined ? values.floatValue : ''
                        }));
                      }}
                      placeholder="Enter Monthly Limit"
                    />
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Status<span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.status}
                      onValueChange={(value) => setFormField({ ...formField, status: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Active</SelectItem>
                        <SelectItem value="N">Inactive</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="flex justify-end gap-5">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    Reset
                  </Button>
                  <Button variant="default">Update</Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
