import { apiConfig } from '@/config/api.config';
import { useManageWalletRuleContext } from '../hooks/useManageWalletRuleContext';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { useCallback, useEffect, useState } from 'react';
import { toast } from 'sonner';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
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 { NumericFormat } from 'react-number-format';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react';
import { initialStateWalletRule, validateFormsWalletRule } from '../Types';
import { WalletProps } from '../../wallet/Types';

const API_URL_WALLET = apiConfig.service_wallet;
const API_URL_MASTERDATA = apiConfig.service_master_data;

const AddDialog = () => {
  const { showAddDialog, handleAddDialog, selectedWalletRule } = useManageWalletRuleContext();
  const { reload } = useDataGrid();
  const { PostData, GetData } = useCallApi();
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formField, setFormField] = useState(initialStateWalletRule);
  const [wallets, setWallets] = useState<WalletProps[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const resetForm = () => {
    setFormField(initialStateWalletRule);
    setErrors({});
  };

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

      try {
        const response = await PostData(`${API_URL_WALLET}/dashboard/wallet_rule`, formField);

        if (response?.status) {
          handleAddDialog(false);
          toast.success('Success Create Wallet Rule');
          reload();

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

          doSaveLogActivity(createActivity);
        } else {
          toast.error(response?.message);
        }
      } catch (error) {
        toast.error('Something went wrong, please try again.');
      } finally {
        setIsSubmitting(false);
      }
    },
    [formField]
  );

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

    if (!validateFormsWalletRule(formField, setErrors)) {
      return;
    }

    doCreateWalletRule(e);
  };

  const getWalletLists = async (sorting: any) => {
    try {
      const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });
      setWallets(response?.data.list);
    } catch (error) {
      console.error('Error fetching wallet', error);
    }
  };

  const selectedWallet = wallets.find((wallet) => wallet.id === formField.id_wallet);
  const filteredGroups = selectedWallet ? selectedWallet.group : [];

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

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

  return (
    <Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
      <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">
            <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>
                    <div className="w-full">
                      <Select
                        value={formField.id_wallet}
                        onValueChange={(value) => {
                          setFormField({ ...formField, id_wallet: value, id_group: '' });
                          setErrors({ ...errors, id_group: '' });
                        }}
                      >
                        <SelectTrigger className={errors.id_wallet ? 'border-red-500' : ''}>
                          <SelectValue placeholder="Select Wallet Type" />
                        </SelectTrigger>
                        <SelectContent>
                          {wallets.map((wallet) => (
                            <SelectItem key={wallet.id} value={wallet.id}>
                              {wallet.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {errors.id_wallet && (
                        <div className="text-red-500 text-xs mt-1">{errors.id_wallet}</div>
                      )}
                    </div>
                  </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>
                    <div className="w-full">
                      <Select
                        value={formField.id_group}
                        onValueChange={(value) => {
                          setFormField({ ...formField, id_group: value });
                          setErrors({ ...errors, id_group: '' });
                        }}
                        disabled={filteredGroups.length === 0}
                      >
                        <SelectTrigger className={errors.id_group ? 'border-red-500' : ''}>
                          <SelectValue placeholder="Select Group Type" />
                        </SelectTrigger>
                        <SelectContent>
                          {filteredGroups.length > 0 ? (
                            filteredGroups.map((group) => (
                              <SelectItem key={group.id} value={group.id}>
                                {group.name}
                              </SelectItem>
                            ))
                          ) : (
                            <SelectItem value="empty">No groups available</SelectItem>
                          )}
                        </SelectContent>
                      </Select>
                      {errors.id_group && (
                        <div className="text-red-500 text-xs mt-1">{errors.id_group}</div>
                      )}
                    </div>
                  </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>
                    <div className="w-full">
                      <NumericFormat
                        className={`input ${errors.max_transaction_per_day ? 'border-red-500' : ''}`}
                        value={formField.max_transaction_per_day ?? null}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            max_transaction_per_day:
                              values.floatValue !== undefined ? values.floatValue : ''
                          }));
                          setErrors({ ...errors, max_transaction_per_day: '' });
                        }}
                        placeholder="Enter Max Transaction Per Day"
                      />
                      {errors.max_transaction_per_day && (
                        <div className="text-red-500 text-xs mt-1">
                          {errors.max_transaction_per_day}
                        </div>
                      )}
                    </div>
                  </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>
                    <div className="w-full">
                      <NumericFormat
                        className={`input ${errors.balance_minimum ? 'border-red-500' : ''}`}
                        value={formField.balance_minimum ?? ''}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            balance_minimum:
                              values.floatValue !== undefined ? values.floatValue : ''
                          }));
                          setErrors({ ...errors, balance_minimum: '' });
                        }}
                        placeholder="Enter Balance Minimum"
                      />
                      {errors.balance_minimum && (
                        <div className="text-red-500 text-xs mt-1">{errors.balance_minimum}</div>
                      )}
                    </div>
                  </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>
                    <div className="w-full">
                      <NumericFormat
                        className={`input ${errors.balance_maximum ? 'border-red-500' : ''}`}
                        value={formField.balance_maximum ?? ''}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            balance_maximum:
                              values.floatValue !== undefined ? values.floatValue : ''
                          }));
                          setErrors({ ...errors, balance_maximum: '' });
                        }}
                        placeholder="Enter Balance Maximum"
                      />
                      {errors.balance_maximum && (
                        <div className="text-red-500 text-xs mt-1">{errors.balance_maximum}</div>
                      )}
                    </div>
                  </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 per Trx<span className="text-red-500">*</span>
                    </label>
                    <div className="w-full">
                      <NumericFormat
                        className={`input ${errors.credit_limit ? 'border-red-500' : ''}`}
                        value={formField.credit_limit ?? ''}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            credit_limit: values.floatValue !== undefined ? values.floatValue : ''
                          }));
                          setErrors({ ...errors, credit_limit: '' });
                        }}
                        placeholder="Enter Credit Limit"
                      />
                      {errors.credit_limit && (
                        <div className="text-red-500 text-xs mt-1">{errors.credit_limit}</div>
                      )}
                    </div>
                  </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>
                    <div className="w-full">
                      <NumericFormat
                        className={`input ${errors.monthly_limit ? 'border-red-500' : ''}`}
                        value={formField.monthly_limit ?? ''}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            monthly_limit: values.floatValue !== undefined ? values.floatValue : ''
                          }));
                          setErrors({ ...errors, monthly_limit: '' });
                        }}
                        placeholder="Enter Monthly Limit"
                      />
                      {errors.monthly_limit && (
                        <div className="text-red-500 text-xs mt-1">{errors.monthly_limit}</div>
                      )}
                    </div>
                  </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>
                    <div className="w-full">
                      <Select
                        value={formField.status}
                        onValueChange={(value) => {
                          setFormField({ ...formField, status: value });
                          setErrors({ ...errors, status: '' });
                        }}
                      >
                        <SelectTrigger className={errors.status ? 'border-red-500' : ''}>
                          <SelectValue placeholder="Select Status" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="Y">Active</SelectItem>
                          <SelectItem value="N">Inactive</SelectItem>
                        </SelectContent>
                      </Select>
                      {errors.status && (
                        <div className="text-red-500 text-xs mt-1">{errors.status}</div>
                      )}
                    </div>
                  </div>
                </div>

                <div className="flex justify-end gap-5">
                  <Button variant="default" type="submit" disabled={isSubmitting}>
                    {isSubmitting ? (
                      <RefreshCw className="animate-spin h-8 w-8 text-white mx-3" />
                    ) : (
                      'Create'
                    )}
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
