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

const API_URL = apiConfig.service_transaction;
const API_URL_MASTER_DATA = apiConfig.service_master_data;
const API_URL_CUSTOMER = apiConfig.service_customer;

interface WalletProps {
  id: string;
  name: string;
}

interface CustomerProps {
  id: string;
  username: string;
  msisdn: string;
}

interface TransactionTypeProps {
  id: string;
  name: string;
}

const EditFeeDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showEditFeeDialog, handleEditFeeDialog, selectedTransferFee } =
    useManageTransferFeeContext();
  const { reload } = useDataGrid();
  const { GetData, PutData } = useCallApi();
  const parsedUser = getAuth()?.user;

  const [wallets, setWallets] = useState<WalletProps[]>([]);
  const [customers, setCustomers] = useState<CustomerProps[]>([]);
  const [transactionTypes, setTransactionTypes] = useState<TransactionTypeProps[]>([]);
  const [transactionTypeName, setTransactionTypeName] = useState('');
  const customersWithNames = customers.map((customer) => ({
    id: customer.id,
    name: customer.username
  }));
  const [customerSearchTerm, setCustomerSearchTerm] = useState('');
  const [showCustomerSearch, setShowCustomerSearch] = useState(false);
  const [open, setOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  const [isLoadingTransferFee, setIsLoadingTransferFee] = useState(false);
  const [isLoadingTransactionType, setIsLoadingTransactionType] = useState(false);
  const [isLoadingWallets, setIsLoadingWallets] = useState(false);
  const [isLoadingCustomers, setIsLoadingCustomers] = useState(false);

  const initialState = {
    name: '',
    description: '',
    transaction_type: '',
    minimum_amount: 0,
    maximum_amount: 0,
    period_start: '',
    period_end: '',
    deduct_amount: 0,
    deduct_percentage: 0,
    fee_amount: 0,
    priority: '',
    status: '',
    status_include: '',
    updated_by: '',
    updated_at: '',
    deduct_from: '',
    deduct_from_account: '',
    credit_to: '',
    credit_destination: '00000000-0000-0000-0000-000000000000',
    credit_destination_account: ''
  };

  const [formField, setFormField] = useState(initialState);

  useEffect(() => {
    const updated_time = new Date();
    const formattedTime = updated_time.toISOString().slice(0, 19).replace('T', ' ');

    if (showEditFeeDialog) {
      setFormField((prevState) => ({
        ...prevState,
        updated_by: parsedUser?.username,
        updated_at: formattedTime
      }));
    }
  }, [showEditFeeDialog, parsedUser?.username]);

  const resetForm = () => {
    if (selectedTransferFee) {
      fetchTransactionFee(selectedTransferFee);
    } else {
      setFormField(initialState);
    }
  };

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

      const requiredFields = [
        'name',
        'description',
        'period_start',
        'period_end',
        'transaction_type',
        'status',
        'status_include',
        'priority',
        'deduct_from',
        'deduct_from_account',
        'credit_to',
        'credit_destination_account'
      ];

      for (const field of requiredFields) {
        if (formField[field as keyof typeof formField] === '') {
          setAlert({
            show: true,
            message: `All required fields must be filled out. Missing: ${field.replace(/_/g, ' ')}`
          });
          setIsSubmitting(false);
          return;
        }
      }

      if (formField.credit_to === 'I' && !formField.credit_destination) {
        setAlert({
          show: true,
          message: 'Credit destination is required when Input Customer is selected'
        });
        setIsSubmitting(false);
        return;
      }

      setAlert({ show: false, message: '' });

      const payload = { ...formField };

      if (formField.credit_to !== 'I') {
        payload.credit_destination = '00000000-0000-0000-0000-000000000000';
      }

      try {
        const response = await PutData(
          `${API_URL}/transactionfees/update/${selectedTransferFee}`,
          payload
        );

        if (response?.status) {
          toast.success('Successfully updated transfer fee');
          reload();
          handleEditFeeDialog(false, null);
          const createActivity = {
            module: 'Manage Transfer Fee',
            description: `Edit Transfer Fee => ${formField.name}`,
            action: 'U'
          };
          doSaveLogActivity(createActivity);
        } else {
          setAlert({ show: true, message: response?.message || 'Failed to update transfer fee' });
        }
      } catch (error) {
        console.error('Error updating transfer fee', error);
        setAlert({ show: true, message: 'An error occurred while updating the transfer fee' });
      } finally {
        setIsSubmitting(false);
      }
    },
    [formField, selectedTransferFee, PutData, reload, handleEditFeeDialog]
  );

  const fetchWallets = useCallback(async () => {
    setIsLoadingWallets(true);
    const params = {
      limit: 100,
      page: 1,
      with_deleted: false,
      order_field: 'Wallets.name',
      order_direction: 'ASC'
    };
    try {
      const response = await GetData(`${API_URL_MASTER_DATA}/wallet/list`, params);
      if (response?.status && response?.data) {
        setWallets(response.data.list);
      } else {
        setWallets([]);
      }
    } catch (error) {
      console.error('Error fetching wallets', error);
      setWallets([]);
    } finally {
      setIsLoadingWallets(false);
    }
  }, [GetData]);

  useEffect(() => {
    if (!showEditFeeDialog) return;
    fetchWallets();
  }, [showEditFeeDialog, fetchWallets]);

  useEffect(() => {
    if (!showEditFeeDialog) return;

    const getCustomerList = async (sorting: any) => {
      setIsLoadingCustomers(true);
      try {
        sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
        const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
          limit: 100,
          page: 1,
          with_deleted: false,
          order_field: sorting[0].id,
          order_direction: sorting[0].desc ? 'DESC' : 'ASC'
        });
        setCustomers(response?.data.list || []);
      } catch (error) {
        console.error('Error fetching customers', error);
      } finally {
        setIsLoadingCustomers(false);
      }
    };

    getCustomerList([{ id: 'id', desc: false }]);
  }, [showEditFeeDialog, GetData]);

  useEffect(() => {
    if (!showEditFeeDialog) return;

    const getTransactionTypeList = async (sorting: any) => {
      setIsLoadingTransactionType(true);
      try {
        sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
        const response = await GetData(`${API_URL}/transactiontype/list`, {
          limit: 100,
          page: 1,
          with_deleted: false,
          order_field: sorting[0].id,
          order_direction: sorting[0].desc ? 'DESC' : 'ASC'
        });
        setTransactionTypes(response?.data.list || []);
      } catch (error) {
        console.error('Error fetching transaction types', error);
      } finally {
        setIsLoadingTransactionType(false);
      }
    };

    getTransactionTypeList([{ id: 'id', desc: false }]);
  }, [showEditFeeDialog, GetData]);

  const formatDate = (dateString: string) => {
    if (!dateString || dateString.includes('0001-01-01')) return '';
    return dateString.split('T')[0];
  };

  const fetchTransactionFee = useCallback(
    async (id: string) => {
      setIsLoadingTransferFee(true);
      try {
        const response = await GetData(`${API_URL}/transactionfees/getdata/${id}`, {});

        if (response?.status) {
          setFormField({
            ...initialState,
            name: response.data.name || '',
            description: response.data.description || '',
            transaction_type: response.data.transaction_type?.id || '',
            minimum_amount: response.data.minimum_amount || 0,
            maximum_amount: response.data.maximum_amount || 0,
            period_start: formatDate(response.data.period_start),
            period_end: formatDate(response.data.period_end),
            deduct_amount: response.data.deduct_amount || 0,
            deduct_percentage: response.data.deduct_percentage || 0,
            fee_amount: response.data.fee_amount || 0,
            priority: response.data.priority || '',
            status: response.data.status || '',
            status_include: response.data.status_include || '',
            deduct_from: response.data.deduct_from || '',
            deduct_from_account: response.data.deduct_from_account?.id || '',
            credit_to: response.data.credit_to || '',
            credit_destination:
              response.data.credit_destination?.id || '00000000-0000-0000-0000-000000000000',
            credit_destination_account: response.data.credit_destination_account?.id || '',
            updated_by: parsedUser?.username,
            updated_at: new Date().toISOString().slice(0, 19).replace('T', ' ')
          });
          
          if (response.data.transaction_type?.name) {
            setTransactionTypeName(response.data.transaction_type.name);
          }
        }
      } catch (error) {
        console.error('Error fetching transaction fee details', error);
        setAlert({ show: true, message: 'Failed to fetch transaction fee details' });
      } finally {
        setIsLoadingTransferFee(false);
      }
    },
    [GetData, parsedUser?.username]
  );

  const hasFetchedRef = useRef(false);

  useEffect(() => {
    if (selectedTransferFee && showEditFeeDialog && !hasFetchedRef.current) {
      fetchTransactionFee(selectedTransferFee);
      hasFetchedRef.current = true;
    }

    if (!showEditFeeDialog) {
      hasFetchedRef.current = false;
    }
  }, [selectedTransferFee, showEditFeeDialog, fetchTransactionFee]);
  const handleCloseDialog = () => {
    setFormField(initialState);
    setAlert({ show: false, message: '' });
    setCustomerSearchTerm('');
    setOpen(false);
    handleEditFeeDialog(false, null);
  };
  useEffect(() => {
    if (!showEditFeeDialog) {
      setCustomerSearchTerm('');
      setOpen(false);
    }
  }, [showEditFeeDialog]);
  const renderSelectWithLoading = (
    value: string,
    onChangeHandler: (value: string) => void,
    options: { id: string; name: string }[] | null,
    placeholder: string,
    isLoading: boolean
  ) => {
    return (
      <Select value={value} onValueChange={onChangeHandler} disabled={isLoading}>
        <SelectTrigger>
          {isLoading ? (
            <div className="flex items-center">
              <div className="animate-pulse bg-gray-200 h-4 w-24 rounded"></div>
              <span className="ml-2">Loading...</span>
            </div>
          ) : (
            <SelectValue placeholder={placeholder} />
          )}
        </SelectTrigger>
        <SelectContent>
          {options &&
            options.map((option) => (
              <SelectItem value={option.id} key={option.id}>
                {option.name}
              </SelectItem>
            ))}
        </SelectContent>
      </Select>
    );
  };

  return (
    <Dialog
      open={showEditFeeDialog}
      onOpenChange={(open) => {
        if (!open) {
          handleCloseDialog();
        }
      }}
    >
      <DialogContent className="container-fixed max-w-[1080px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
        <DialogTitle></DialogTitle>
        <DialogDescription></DialogDescription>
        <DialogHeader className="p-5 border-0">
          <div className="flex items-center justify-between flex-wrap grow">
            <div className="flex flex-col justify-center">
              <h1 className="text-xl font-semibold leading-none text-gray-900">
                Edit Transfer Fee
              </h1>
            </div>
            <div
              className="cursor-pointer hover:opacity-100 opacity-50"
              onClick={handleCloseDialog}
            >
              <KeenIcon icon="cross" className="text-1.5xl" />
            </div>
          </div>
        </DialogHeader>
        <DialogBody className="max-h-[1080px] overflow-y-auto">
          {alert.show && (
            <div className="sticky top-0 z-10 bg-white p-3">
              <Alert variant="danger" className="mb-3">
                <h3>{alert.message}</h3>
              </Alert>
            </div>
          )}
          
          {isLoadingTransferFee ? (
            <div className="flex flex-col items-center justify-center p-8">
              <div className="animate-pulse flex space-x-4 w-full">
                <div className="flex-1 space-y-4 py-1">
                  <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                  <div className="space-y-2">
                    <div className="h-4 bg-gray-200 rounded"></div>
                    <div className="h-4 bg-gray-200 rounded w-5/6"></div>
                  </div>
                </div>
              </div>
              <p className="mt-4 text-gray-500">Loading transfer fee details...</p>
            </div>
          ) : (
            <form action="" onSubmit={doUpdateTransferFee}>
              <div className="card flex flex-col gap-5">
                <div className="card-body grid gap-5 p-0">
                  <div className="w-full">
                    <label className="form-label">
                      Transaction Type ID <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <Input
                        className="input bg-gray-100"
                        type="text"
                        value={isLoadingTransactionType ? '' : transactionTypeName}
                        readOnly
                      />
                      {isLoadingTransactionType && (
                        <div className="absolute inset-0 flex items-center justify-start bg-gray-100 px-3">
                          <div className="flex items-center">
                            <div className="animate-pulse bg-gray-200 h-4 w-24 rounded"></div>
                            <span className="ml-2 text-gray-500">Loading transaction type...</span>
                          </div>
                        </div>
                      )}
                      <input 
                        type="hidden" 
                        name="transaction_type" 
                        value={formField.transaction_type} 
                      />
                    </div>
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">
                      Transfer Fee Name <span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="text"
                      autoComplete="off"
                      value={formField.name}
                      onChange={({ target }) =>
                        setFormField((prev) => ({ ...prev, name: target.value }))
                      }
                    />
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">
                      Description <span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="text"
                      autoComplete="off"
                      value={formField.description}
                      onChange={({ target }) =>
                        setFormField((prev) => ({ ...prev, description: target.value }))
                      }
                    />
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">Minimum Amount</label>
                    <NumericFormat
                      className="input"
                      value={formField.minimum_amount}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          minimum_amount: values.floatValue || 0
                        }));
                      }}
                      placeholder="Enter Minimum Amount"
                    />
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">Maximum Amount</label>
                    <NumericFormat
                      className="input"
                      value={formField.maximum_amount}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          maximum_amount: values.floatValue || 0
                        }));
                      }}
                      placeholder="Enter Maximum Amount"
                    />
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">
                      Period Start <span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="date"
                      autoComplete="off"
                      value={formField.period_start}
                      onChange={({ target }) =>
                        setFormField((prev) => ({ ...prev, period_start: target.value }))
                      }
                    />
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">
                      Period End <span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="date"
                      autoComplete="off"
                      value={formField.period_end}
                      onChange={({ target }) =>
                        setFormField((prev) => ({ ...prev, period_end: target.value }))
                      }
                    />
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">Deduct Amount</label>
                    <NumericFormat
                      className="input"
                      value={formField.deduct_amount}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          deduct_amount: values.floatValue || 0
                        }));
                      }}
                      placeholder="Enter Deduct Amount"
                    />
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">Deduct Percentage</label>
                    <NumericFormat
                      className="input"
                      value={formField.deduct_percentage}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          deduct_percentage: values.floatValue || 0
                        }));
                      }}
                      placeholder="Enter Deduct Percentage"
                    />
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">Fee Amount</label>
                    <NumericFormat
                      className="input"
                      value={formField.fee_amount}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          fee_amount: values.floatValue || 0
                        }));
                      }}
                      placeholder="Enter Fee Amount"
                    />
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">
                      Deduct From <span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.deduct_from}
                      onValueChange={(value) => setFormField({ ...formField, deduct_from: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Deduct From" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="D">Destination Member</SelectItem>
                        <SelectItem value="S">Source Member</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">
                      Deduct From Destination <span className="text-red-500">*</span>
                    </label>
                    {renderSelectWithLoading(
                      formField.deduct_from_account,
                      (value) => setFormField({ ...formField, deduct_from_account: value }),
                      wallets,
                      'Select Wallet',
                      isLoadingWallets
                    )}
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">
                      Credit To <span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.credit_to}
                      onValueChange={(value) =>
                        setFormField({
                          ...formField,
                          credit_to: value,
                          credit_destination:
                            value === 'I' ? '' : '00000000-0000-0000-0000-000000000000'
                        })
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Credit To" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="D">Destination Member</SelectItem>
                        <SelectItem value="S">Source Member</SelectItem>
                        <SelectItem value="I">Input Customer</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  
                  {formField.credit_to === 'I' && (
  <div className="w-full">
    <label className="form-label">
      Credit Destination <span className="text-red-500">*</span>
    </label>
    <div className="relative">
      <div 
        className="flex w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 cursor-pointer"
        onClick={() => setOpen(!open)}
      >
        <span className="truncate">
          {customers.find(customer => customer.id === formField.credit_destination)?.username || 'Search customer...'}
        </span>
          <path d="m6 9 6 6 6-6"></path>
      </div>
      
      {open && (
        <div className="absolute left-0 right-0 top-full z-50 mt-1 max-h-52 overflow-auto rounded-md border border-gray-200 bg-white shadow-lg">
          <div className="sticky top-0 bg-white p-2 border-b">
            <Input
              className="h-8 text-sm"
              type="text"
              placeholder="Search customer..."
              value={customerSearchTerm}
              onChange={(e) => setCustomerSearchTerm(e.target.value)}
              autoComplete="off"
              onClick={(e) => e.stopPropagation()}
              autoFocus
            />
          </div>
          <div>
            {customers
              .filter(customer => 
                customer.username.toLowerCase().includes(customerSearchTerm.toLowerCase()) ||
                customer.msisdn.includes(customerSearchTerm)
              )
              .map(customer => (
                <div 
                  key={customer.id} 
                  className="cursor-pointer px-3 py-1.5 text-sm hover:bg-gray-100"
                  onClick={() => {
                    setFormField({
                      ...formField,
                      credit_destination: customer.id
                    });
                    setOpen(false);
                  }}
                >
                  {customer.username}
                </div>
              ))}
            {customers.filter(customer => 
              customer.username.toLowerCase().includes(customerSearchTerm.toLowerCase()) ||
              customer.msisdn.includes(customerSearchTerm)
            ).length === 0 && (
              <div className="px-3 py-2 text-sm text-gray-500">No customer found</div>
            )}
          </div>
        </div>
      )}
    </div>
  </div>
)}



                  
                  <div className="w-full">
                    <label className="form-label">
                      Credit Destination Account <span className="text-red-500">*</span>
                    </label>
                    {renderSelectWithLoading(
                      formField.credit_destination_account,
                      (value) => setFormField({ ...formField, credit_destination_account: value }),
                      wallets,
                      'Select Wallet',
                      isLoadingWallets
                    )}
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">
                      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 className="w-full">
                    <label className="form-label">
                      Status Include <span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.status_include}
                      onValueChange={(value) => setFormField({ ...formField, status_include: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Yes</SelectItem>
                        <SelectItem value="N">No</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div className="w-full">
                    <label className="form-label">
                      Priority <span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.priority}
                      onValueChange={(value) => setFormField({ ...formField, priority: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Priority" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Yes</SelectItem>
                        <SelectItem value="N">No</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div className="flex justify-end pt-2.5 gap-5">
                    <Button
                      variant={'outline'}
                      type="button"
                      onClick={resetForm}
                    >
                      Reset
                    </Button>
                    <Button
                      variant={'default'}
                      type="submit"
                      disabled={
                        isSubmitting ||
                        isLoadingTransferFee ||
                        isLoadingTransactionType ||
                        isLoadingWallets ||
                        isLoadingCustomers
                      }
                    >
                      {isSubmitting ? 'Saving...' : 'Save Changes'}
                    </Button>
                  </div>
                </div>
              </div>
            </form>
          )}
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export  {EditFeeDialog};