import { useCallback, useEffect, useRef, useState } from 'react';
import { useManageTransferFeeContext } from '../hooks/useManageTransferFeeContext';
import { NumericFormat } from 'react-number-format';
import {
  Alert,
  Container,
  DataGridColumnHeader,
  DataGridInner,
  KeenIcon,
  useDataGrid
} from '@/components';
import { useCallApi } from '@/hooks';
3;
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { getAuth } from '@/auth';
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TableRow
} from '@/components/ui/table';
import { apiConfig } from '@/config/api.config';
import { set } from 'date-fns';

interface TransactionTypeProps {
  id: string;
  name: string;
}
interface WalletProps {
  id: string;
  name: string;
}
interface CustomerProps {
  id: string;
  fullname: string;
  msisdn: string;
}
const API_URL = apiConfig.service_transaction;
const API_URL_MASTER_DATA = apiConfig.service_master_data;
const API_URL_CUSTOMER = apiConfig.service_customer;

const AddFeeDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { reload } = useDataGrid();
  const { PostData, PutData, GetData } = useCallApi();
  const {
    showAddFeeDialog,
    handleAddFeeDialog,
    handleEditFeeDialog,
    selectedTransferFee,
    transactionTypeId
  } = useManageTransferFeeContext();
  const [deductSearchTerm, setDeductSearchTerm] = useState('');
  const [creditSearchTerm, setCreditSearchTerm] = useState('');

  const [open, setOpen] = useState(false);

  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const [transactionTypes, setTransactionTypes] = useState<TransactionTypeProps[]>([]);
  const [wallets, setWallets] = useState<WalletProps[]>([]);
  const [deductFilteredCustomers, setDeductFilteredCustomers] = useState<CustomerProps[]>([]);
  const [creditFilteredCustomers, setCreditFilteredCustomers] = useState<CustomerProps[]>([]);
  const [isSearchingDeductCustomers, setIsSearchingDeductCustomers] = useState(false);
  const [isSearchingCreditCustomers, setIsSearchingCreditCustomers] = useState(false);
  const [transactionTypeName, setTransactionTypeName] = useState('');

  const [isLoadingTransactionType, setIsLoadingTransactionType] = useState(false);
  const [isLoadingWallets, setIsLoadingWallets] = useState(false);

  const [openDeductOrigin, setOpenDeductOrigin] = useState(false);
  const [openCreditDestination, setOpenCreditDestination] = useState(false);

  const [errors, setErrors] = useState<Record<string, string>>({});
  const initialState = {
    name: '',
    description: '',
    transaction_type: '',
    minimum_amount: 0,
    maximum_amount: 0,
    period_start: '',
    period_end: '',
    deduct_amount: 0,
    deduct_percentage: 0,
    status: '',
    status_include: '',
    created_by: '',
    created_at: '',
    deduct_from: '',
    deduct_origin: '00000000-0000-0000-0000-000000000000',
    deduct_from_account: '',
    credit_to: '',
    credit_destination: '00000000-0000-0000-0000-000000000000',
    credit_destination_account: '',
    deduct_when: 'A'
  };

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

  const resetForm = () => {
    setFormField(initialState);
    setTransactionTypeName('');
    setDeductFilteredCustomers([]);
    setCreditFilteredCustomers([]);
    setDeductSearchTerm('');
    setCreditSearchTerm('');
  };

  const handleCloseDialog = () => {
    setFormField(initialState);
    setAlert({ show: false, message: '' });
    setDeductSearchTerm('');
    setCreditSearchTerm('');
    setOpenCreditDestination(false);
    setOpenDeductOrigin(false);
    setOpen(false);
    handleEditFeeDialog(false, null);
  };

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showTransactionFeeDialog, setShowTransactionFeeDialog] = useState(false);
  const parsedUser = getAuth()?.user;

  const useDebounce = (value: string, delay: number) => {
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
      const handler = setTimeout(() => {
        setDebouncedValue(value);
      }, delay);

      return () => {
        clearTimeout(handler);
      };
    }, [value, delay]);

    return debouncedValue;
  };
  const debouncedDeductSearchTerm = useDebounce(deductSearchTerm, 500);
  const debouncedCreditSearchTerm = useDebounce(creditSearchTerm, 500);
  useEffect(() => {
    if (showAddFeeDialog && transactionTypeId) {
      setIsLoadingTransactionType(true);

      setFormField((prev) => ({
        ...prev,
        transaction_type: transactionTypeId
      }));

      const getTransactionTypeDetails = async () => {
        try {
          const response = await GetData(
            `${API_URL}/transactiontype/getdata/${transactionTypeId}`,
            {}
          );
          if (response?.status && response?.data) {
            setTransactionTypeName(response.data.name);
          }
        } catch (error) {
          console.error('Error fetching transaction type details', error);
        } finally {
          setIsLoadingTransactionType(false);
        }
      };

      getTransactionTypeDetails();
    }
  }, [showAddFeeDialog, transactionTypeId, GetData]);

  useEffect(() => {
    if (!showAddFeeDialog) {
      setDeductSearchTerm('');
      setCreditSearchTerm('');
      setOpen(false);
    }
  }, [showAddFeeDialog]);

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

    if (showAddFeeDialog) {
      setFormField((prev) => ({
        ...prev,
        created_by: parsedUser?.username,
        created_at: formattedTime
      }));
    }
  }, [showAddFeeDialog, parsedUser?.username]);

  useEffect(() => {
    if (!showAddFeeDialog) 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 }]);
  }, [showAddFeeDialog, GetData]);

  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 (!showAddFeeDialog) return;
    fetchWallets();
  }, [showAddFeeDialog, fetchWallets]);

  const searchDeductCustomers = useCallback(
    async (searchTerm: string) => {
      setIsSearchingDeductCustomers(true);
      try {
        let response;
        if (!searchTerm.trim()) {
          response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
            limit: 20,
            page: 1,
            with_deleted: false,
            order_field: 'username',
            order_direction: 'ASC'
          });
        } else {
          const filters = [{ id: 'fullname', value: searchTerm.trim() }];
          response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
            limit: 20,
            page: 1,
            with_deleted: false,
            order_field: 'username',
            order_direction: 'ASC',
            filter: JSON.stringify(filters),
            specialFilter: true
          });
        }
        setDeductFilteredCustomers(response?.data?.list || []);
      } catch (error) {
        console.error('Error searching deduct customers', error);
        setDeductFilteredCustomers([]);
      } finally {
        setIsSearchingDeductCustomers(false);
      }
    },
    [GetData]
  );
  useEffect(() => {
    if (openDeductOrigin && formField.deduct_from === 'I') {
      searchDeductCustomers(debouncedDeductSearchTerm);
    }
  }, [debouncedDeductSearchTerm, openDeductOrigin, formField.deduct_from, searchDeductCustomers]);

  const searchCreditCustomers = useCallback(
    async (searchTerm: string) => {
      setIsSearchingCreditCustomers(true);
      try {
        let response;
        if (!searchTerm.trim()) {
          response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
            limit: 20,
            page: 1,
            with_deleted: false,
            order_field: 'username',
            order_direction: 'ASC'
          });
        } else {
          const filters = [{ id: 'fullname', value: searchTerm.trim() }];
          response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
            limit: 20,
            page: 1,
            with_deleted: false,
            order_field: 'username',
            order_direction: 'ASC',
            filter: JSON.stringify(filters),
            specialFilter: true
          });
        }
        setCreditFilteredCustomers(response?.data?.list || []);
      } catch (error) {
        console.error('Error searching credit customers', error);
        setCreditFilteredCustomers([]);
      } finally {
        setIsSearchingCreditCustomers(false);
      }
    },
    [GetData]
  );
  useEffect(() => {
    if (openCreditDestination && formField.credit_to === 'I') {
      searchCreditCustomers(debouncedCreditSearchTerm);
    }
  }, [
    debouncedCreditSearchTerm,
    openCreditDestination,
    formField.credit_to,
    searchCreditCustomers
  ]);

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

      const requiredFields = [
        'name',
        'description',
        'period_start',
        'period_end',
        'transaction_type',
        'status',
        'status_include',
        '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;
      }

      if (formField.deduct_from === 'I' && !formField.deduct_origin) {
        setAlert({
          show: true,
          message: 'Deduct Origin is required when Input 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';
      }

      if (formField.deduct_from !== 'I') {
        payload.deduct_origin = '00000000-0000-0000-0000-000000000000';
      }
      try {
        const response = await PostData(`${API_URL}/transactionfees/create`, payload);

        if (response?.status) {
          toast.success('Successfully created transfer fee');
          reload();
          resetForm();
          handleAddFeeDialog(false);

          const createActivity = {
            module: 'Manage Transfer Fee',
            description: `Create Transfer Fee => ${formField.name}`,
            action: 'C'
          };
          doSaveLogActivity(createActivity);
        } else {
          setAlert({ show: true, message: response?.message || 'Failed to create transfer fee' });
        }
      } catch (error) {
        console.error('Error creating transfer fee', error);
        setAlert({ show: true, message: 'An error occurred while creating the transfer fee' });
      } finally {
        setIsSubmitting(false);
      }
    },
    [formField, PostData, reload, handleAddFeeDialog]
  );

  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>
    );
  };

  useEffect(() => {
    if (formField.status_include === 'N') {
      setFormField((prev) => ({ ...prev, deduct_when: 'A' }));
    }
  }, [formField.status_include]);

  return (
    <Dialog
      open={showAddFeeDialog}
      onOpenChange={(open) => {
        if (!open) {
          handleAddFeeDialog(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">Add Transfer Fee</h1>
            </div>
            <div
              className="cursor-pointer hover:opacity-100 opacity-50"
              onClick={() => {
                handleAddFeeDialog(false);
                resetForm();
              }}
            >
              <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>
          )}
          <form action="" onSubmit={doCreateTransferType}>
            <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>
                  {transactionTypeId ? (
                    <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>
                      )}
                    </div>
                  ) : (
                    renderSelectWithLoading(
                      formField.transaction_type,
                      (transaction_type) => setFormField((prev) => ({ ...prev, transaction_type })),
                      transactionTypes,
                      'Select Transaction Type',
                      isLoadingTransactionType
                    )
                  )}
                </div>
                <div className="w-full">
                  <label className="form-label">
                    Transfer Free 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 ? formField.period_start.split('T')[0] : ''}
                    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 ? formField.period_end.split('T')[0] : ''}
                    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">
                    Deduct From <span className="text-red-500">*</span>
                  </label>
                  <Select
                    value={formField.deduct_from}
                    onValueChange={(value) =>
                      setFormField({
                        ...formField,
                        deduct_from: value,
                        deduct_origin: value === 'I' ? '' : '00000000-0000-0000-0000-000000000000'
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select Deduct From" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="D">Destination Member</SelectItem>
                      <SelectItem value="S">Source Member</SelectItem>
                      <SelectItem value="I">Input</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                {formField.deduct_from === 'I' && (
                  <div className="w-full">
                    <label className="form-label">
                      Deduct Origin <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={() => {
                          setOpenDeductOrigin(!openDeductOrigin);
                          if (!openDeductOrigin && deductSearchTerm.trim() === '') {
                            searchDeductCustomers('');
                          }
                        }}
                      >
                        <span className="truncate">
                          {deductFilteredCustomers.find(
                            (customer) => customer.id === formField.deduct_origin
                          )?.fullname || 'Search customer...'}
                        </span>
                      </div>

                      {openDeductOrigin && (
                        <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={deductSearchTerm}
                              onChange={(e) => {
                                const value = e.target.value;
                                setDeductSearchTerm(value);
                              }}
                              autoComplete="off"
                              onClick={(e) => e.stopPropagation()}
                              autoFocus
                            />
                          </div>
                          <div>
                            {isSearchingDeductCustomers ? (
                              <div className="px-3 py-2 text-sm text-gray-500">Searching...</div>
                            ) : (
                              deductFilteredCustomers.map((customer) => (
                                <div
                                  key={customer.id}
                                  className="cursor-pointer px-3 py-1.5 text-sm hover:bg-gray-100"
                                  onClick={() => {
                                    setFormField({ ...formField, deduct_origin: customer.id });
                                    setOpenDeductOrigin(false);
                                  }}
                                >
                                  {customer.fullname}
                                </div>
                              ))
                            )}

                            {!isSearchingDeductCustomers &&
                              deductFilteredCustomers.length === 0 &&
                              deductSearchTerm.trim() && (
                                <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">
                    Deduct From Account <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={() => {
                          setOpenCreditDestination(!openCreditDestination);
                          if (!openCreditDestination && creditSearchTerm.trim() === '') {
                            searchCreditCustomers('');
                          }
                        }}
                      >
                        <span className="truncate">
                          {creditFilteredCustomers.find(
                            (customer) => customer.id === formField.credit_destination
                          )?.fullname || 'Search customer...'}
                        </span>
                      </div>

                      {openCreditDestination && (
                        <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={creditSearchTerm}
                              onChange={(e) => {
                                const value = e.target.value;
                                setCreditSearchTerm(value);
                              }}
                              autoComplete="off"
                              onClick={(e) => e.stopPropagation()}
                              autoFocus
                            />
                          </div>
                          <div>
                            {isSearchingCreditCustomers ? (
                              <div className="px-3 py-2 text-sm text-gray-500">Searching...</div>
                            ) : (
                              creditFilteredCustomers.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 });
                                    setOpenCreditDestination(false);
                                  }}
                                >
                                  {customer.fullname}
                                </div>
                              ))
                            )}

                            {!isSearchingCreditCustomers &&
                              creditFilteredCustomers.length === 0 &&
                              creditSearchTerm.trim() && (
                                <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>
                {formField.status_include === 'Y' && (
                  <div className="w-full">
                    <label className="form-label">
                      Deduct When <span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.deduct_when}
                      onValueChange={(value) => setFormField({ ...formField, deduct_when: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Deduct When" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="A">After</SelectItem>
                        <SelectItem value="B">Before</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                )}

                <div className="flex justify-end pt-2.5 gap-5">
                  <Button
                    variant={'outline'}
                    type="reset"
                    onClick={() => {
                      resetForm();
                    }}
                  >
                    Reset
                  </Button>
                  <Button
                    variant={'default'}
                    type="submit"
                    disabled={isSubmitting || isLoadingTransactionType || isLoadingWallets}
                  >
                    {isSubmitting ? 'Saving...' : 'Save Changes'}
                  </Button>
                </div>
              </div>
            </div>
          </form>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddFeeDialog;
