import { useCallback, useEffect, useMemo, 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';
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 { ManageTransferFeeContext } from '../hooks/ManageTransferFeeContext';
import { ColumnDef } from '@tanstack/react-table';
import { ManageTransferFeeContextProvider } from '../../transferfee/hooks/ManageTransferFeeContext';
import { apiConfig } from '@/config/api.config';
import { get } from 'http';

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

const API_URL = apiConfig.service_transaction;

const AddFeeDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { reload } = useDataGrid();
  const { PostData, PutData, GetData } = useCallApi();
  const { showAddFeeDialog, handleAddFeeDialog, handleEditFeeDialog, selectedTransferFee } =
    useManageTransferFeeContext();
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const [transactionTypes, setTransactionTypes] = useState<TransactionTypeProps[]>([]);

  const initialState = {
    name: '',
    description: '',
    transaction_type: '',
    minimum_amount: 0,
    maximum_amount: 0,
    period_start: '',
    period_end: '',
    deduct_amount: 0,
    deduct_percentage: 0,
    priority: false,
    status: '',
    status_include: '',
    created_by: '',
    created_at: ''
  };

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

  const resetForm = () => {
    setFormField(initialState);
  };

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

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    // setIsSubmitting(true);
    const payload = {
      name: formField.name,
      description: formField.description,
      period_start: formField.period_start,
      period_end: formField.period_end,
      minimum_amount: formField.minimum_amount,
      maximum_amount: formField.maximum_amount,
      deduct_amount: formField.deduct_amount,
      deduct_percentage: formField.deduct_percentage,
      transaction_type: formField.transaction_type,
      status: formField.status,
      status_include: formField.status_include,
      priority: formField.priority ? 'Y' : 'N'
    };
  };
  useEffect(() => {
    const created_time = new Date();
    const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');

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

  useEffect(() => {
    if (!showAddFeeDialog) 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'
        });
        setTransactionTypes(response?.data.list || []);
      } catch (error) {
        console.error('Error fetching customer', error);
      }
    };

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

  const doCreateTransferType = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      for (const key in formField) {
        if (
          formField[key as keyof typeof formField] === '' ||
          formField[key as keyof typeof formField] === 0
        ) {
          setAlert({ show: true, message: 'All fields must be filled out' });
          return;
        }
      }

      setAlert({ show: false, message: '' });
      const response = await PostData(`${API_URL}/transactionfees/create`, {
        ...formField
      });
      // console.log(response);
      if (response?.status) {
        toast.success('Success Create Transfer Fee');
        reload();
        resetForm();
        handleAddFeeDialog(false);
      } else {
        setAlert({ show: true, message: response?.message || 'Failed to create transfer fee' });
      }
    },
    [formField]
  );

  return (
    <Dialog open={showAddFeeDialog} onOpenChange={(open) => handleAddFeeDialog(open)}>
      <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 && <Alert variant="danger">{alert.message}</Alert>}
          <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">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 Max Transaction Per Day"
                  />
                </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 Max Transaction Per Day"
                  />
                </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 Max Transaction Per Day"
                  />
                </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 Max Transaction Per Day"
                  />
                </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 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 ? 'Y' : 'N'}
                    onValueChange={(value) =>
                      setFormField((prev) => ({ ...prev, priority: value === 'Y' }))
                    }
                  >
                    <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="reset"
                    onClick={() => {
                      resetForm();
                    }}
                  >
                    Reset
                  </Button>
                  <Button variant={'default'} type="submit" disabled={isSubmitting}>
                    {isSubmitting ? 'Saving...' : 'Save Changes'}
                  </Button>
                </div>
              </div>
            </div>
          </form>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddFeeDialog;
