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 { ManageTransferFeeContextProvider } from '../../transferfee/hooks/ManageTransferFeeContext';
import AddFeeDialog from '../../transferfee/blocks/AddDialog';

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

interface WalletProps {
  Wallet_id: string;
  Wallet_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 [wallets, setWallets] = useState<WalletProps[]>([]);
  const { GetData, PutData } = useCallApi();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [transactionTypes, setTransactionTypes] = useState<TransactionTypeProps[]>([]);
  const parsedUser = getAuth()?.user;
  const [customers, setCustomers] = useState<CustomerProps[]>([]);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const [formField, setFormField] = useState({
    name: '',
    description: '',
    minimum_amount: 0,
    maximum_amount: 0,
    period_start: '',
    period_end: '',
    deduct_amount: 0,
    deduct_percentage: 0,
    priority: '',
    status: '',
    status_include: '',
    transaction_type: '',
    updated_by: '',
    updated_at: ''
  });
  useEffect(() => {
    const updated_time = new Date();
    const formattedTime = updated_time.toISOString().slice(0, 19).replace('T', ' ');

    if (showEditFeeDialog) {
      setFormField({
        ...formField,
        updated_by: parsedUser?.username,
        updated_at: formattedTime
      });
    }
  }, [showEditFeeDialog]);
  /* actions */
  const doUpdateTransferFee = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      const response = await PutData(`${API_URL}/transactionfees/update/${selectedTransferFee}`, {
        ...formField,      });
      if (response?.status) {
        handleEditFeeDialog(false, null);
        toast.success('Success Update User');
        reload();
      } else {
        setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
      }
    },
    [formField, selectedTransferFee]
  );
  const fetchWallets = useCallback(async () => {
    const params = {
      limit: 100,
      page: 1,
      with_deleted: false,
      order_field: 'name',
      order_direction: 'ASC',
      filter: JSON.stringify({
        status: 'Y'
      })
    };
    const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, params);
    if (response?.status && response?.data) {
      setWallets(response.data.list);
    } else {
      setWallets([]);
    }
  }, []);

  useEffect(() => {
    fetchWallets();
  }, [fetchWallets]);

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

    const getCustomerList = async (sorting: any) => {
      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 customer', error);
      }
    };

    getCustomerList([{ id: 'msisdn', desc: false }]);
  }, []);
  useEffect(() => {
    if (!showEditFeeDialog) return;

    const getTransactionTypeList = async (sorting: any) => {
      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'
        });
        // console.log('Transaction Type: ', response?.data.list);
        setTransactionTypes(response?.data.list);
      } catch (error) {
        console.error('Error fetching Transaction Type', error);
      }
    };

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

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

    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        name: response.data.name,
        description: response.data.description,
        minimum_amount: response.data.minimum_amount,
        maximum_amount: response.data.maximum_amount,
        period_start: response.data.period_start,
        period_end: response.data.period_end,
        deduct_amount: response.data.deduct_amount,
        deduct_percentage: response.data.deduct_percentage,
        priority: response.data.priority,
        status: response.data.status,
        status_include: response.data.status_include,
        transaction_type: response.data.transaction_type.id
      }));
    }
  }, []);

  useEffect(() => {
    if (selectedTransferFee) {
      fetchTransactionFee(selectedTransferFee);
    }
  }, [selectedTransferFee]);
  const resetForm = () => {
    setFormField({
      name: '',
      description: '',
      minimum_amount: 0,
      maximum_amount: 0,
      period_start: '',
      period_end: '',
      deduct_amount: 0,
      deduct_percentage: 0,
      priority: '',
      status: '',
      status_include: '',
      transaction_type: '',
      updated_by: '',
      updated_at: ''
    });
  };

  return (
    <Dialog open={showEditFeeDialog} onOpenChange={(open) => handleEditFeeDialog(open, null)}>
      <DialogContent className="container-fixed max-w-[1080px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
        <DialogHeader className="p-5 border-0">
          <DialogTitle></DialogTitle>
          <DialogDescription></DialogDescription>
          <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">
                Update Transaction Fee
              </h1>
              <div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
            </div>
            <div
              className="cursor-pointer hover:opacity-100 opacity-50"
              onClick={() => handleEditFeeDialog(false, null)}
            >
              <KeenIcon icon="cross" className="text-1.5xl" />
            </div>
          </div>
        </DialogHeader>
        <DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
          <div className="flex flex-col px-0">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}
            <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">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 <span className="text-red-500">*</span></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 <span className="text-red-500">*</span></label>
                    <NumericFormat
                      className="input"
                      value={formField.maximum_amount}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          maximum_amount: values.floatValue || 0
                        }));
                      }}
                      placeholder="Enter Minimum 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 <span className="text-red-500">*</span></label>
                    <NumericFormat
                      className="input"
                      value={formField.deduct_amount}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          deduct_amount: values.floatValue || 0
                        }));
                      }}
                      placeholder="Enter Minimum Amount"
                    />
                  </div>
                  <div className="w-full">
                    <label className="form-label">Deduct Percentage <span className="text-red-500">*</span></label>
                    <NumericFormat
                      className="input"
                      value={formField.deduct_percentage}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          deduct_percentage: values.floatValue || 0
                        }));
                      }}
                      placeholder="Enter Minimum Amount"
                    />
                  </div>
                  <div className="w-full">
                    <label className="form-label">Transacsion Type ID <span className="text-red-500">*</span></label>
                    <Select
                      value={formField.transaction_type}
                      onValueChange={(transaction_type) =>
                        setFormField((prev) => ({ ...prev, transaction_type }))
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Wallet" />
                      </SelectTrigger>
                      <SelectContent>
                        {transactionTypes.map((transactiontype, idx) => (
                          <SelectItem value={transactiontype.id} key={transactiontype.id}>
                            {transactiontype.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </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 Included <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="w-full">
                  <label className="form-label">Priotity <span className="text-red-500">*</span></label>
                  <Select
                    value={formField.priority}
                    onValueChange={(value) => setFormField({ ...formField, priority: value })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select Status" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Y">Y</SelectItem>
                      <SelectItem value="N">N</SelectItem>
                    </SelectContent>
                  </Select>
                </div> */}

                  {/* <div className="w-full">
  <label className="form-label">Priority <span className="text-red-500">*</span></label>
  <Select
    value={formField.priority ? 'Y' : 'N'}
    onValueChange={(value) =>
      setFormField({ ...formField, priority: value === 'Y' })
    }
  >
    <SelectTrigger>
      <SelectValue placeholder="Select Priority" />
    </SelectTrigger>
    <SelectContent>
      <SelectItem value="Y">Y</SelectItem>
      <SelectItem value="N">N</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}>
                      {isSubmitting ? 'Saving...' : 'Save Changes'}
                    </Button>
                  </div>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export { EditFeeDialog };
