import { apiConfig } from '@/config/api.config';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useManageTransferTypeContext } from '../hooks/useManageTransferTypeContext';
import {
  Alert,
  Container,
  DataGridColumnHeader,
  DataGridInner,
  KeenIcon,
  useDataGrid
} from '@/components';
import { useCallApi } from '@/hooks';
import { NumericFormat } from 'react-number-format';
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 { getAuth } from '@/auth';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { doSaveLogActivity } from '@/actions/GlobalActions';

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

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

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

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const [open, setOpen] = useState(false);
  const { GetData } = useCallApi();
  const { showAddDialog, handleAddDialog, selectedTransferType } = useManageTransferTypeContext();
  const [wallets, setWallets] = useState<WalletProps[]>([]);
  const [customers, setCustomers] = useState<CustomerProps[]>([]);
  const { reload } = useDataGrid();
  const { PostData, PutData } = useCallApi();
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  const initialState = {
    name: '',
    description: '',
    wallet_origin: '',
    wallet_destination: '',

    minimum_amount: 0,
    maximum_amount: 0,
    max_transaction_per_day: 0,
    status: '',
    type: '',
    status_approval: '',
    created_by: '',
    created_at: ''
  };

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

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

  const parsedUser = getAuth()?.user;

  const validateForm = () => {
    const requiredFields = [
      'name',
      'description',
      'wallet_origin',
      'wallet_destination',
      'status',
      'status_approval'
    ];

    const missingFields = requiredFields.filter(
      (field) =>
        formField[field as keyof typeof formField] === '' ||
        formField[field as keyof typeof formField] === null ||
        formField[field as keyof typeof formField] === undefined
    );

    if (missingFields.length > 0) {
      setAlert({
        show: true,
        message: `Please fill out all required fields: ${missingFields.join(', ')}`
      });
      return false;
    }

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

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

    if (!validateForm()) {
      setIsSubmitting(false);
      return;
    }

    doCreateTransferType(formField)
      .then((success) => {
        if (success) {
          handleAddDialog(false);
          toast.success('Success Create Transfer Type');
          reload();
          resetForm();
          const createActivity = {
            module: 'Manage Transfer Type',
            description: `Create Transfer Type => ${formField.name}`,
            action: 'C'
          };

          doSaveLogActivity(createActivity);
        }
      })
      .finally(() => {
        setIsSubmitting(false);
      });
  };

  const doCreateTransferType = useCallback(
    async (data: typeof formField) => {
      try {
        const response = await PostData(`${API_URL}/transactiontype/create`, data);

        if (response?.status) {
          setAlert({ show: false, message: '' });
          return true;
        } else {
          setAlert({ show: true, message: response?.message || 'Failed to create transfer type' });
          return false;
        }
      } catch (error) {
        setAlert({
          show: true,
          message:
            error instanceof Error
              ? error.message
              : 'An error occurred while creating transfer type'
        });
        return false;
      }
    },
    [PostData]
  );

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

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

  useEffect(() => {
    if (!showAddDialog) return;
    const getCustomerList = async (sorting: any) => {
      try {
        sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;

        const response = await GetData(`${API_URL3_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: 'id', desc: false }]);
  }, [showAddDialog]);

  const fetchWallets = useCallback(async () => {
    const params = {
      limit: 100,
      page: 1,
      with_deleted: false,
      order_field: 'wallets.name',
      order_direction: 'ASC'
    };
    const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, params);
    // console.log(response)
    if (response?.status && response?.data) {
      setWallets(response.data.list);
    } else {
      setWallets([]);
    }
  }, []);

  useEffect(() => {
    if (!showAddDialog) return;
    fetchWallets();
  }, [showAddDialog]);
  // console.log(formField)
  return (
    <Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
      <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">
                Add Transaction Type
              </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={() => {
                handleAddDialog(false);
                resetForm();
              }}
            >
              <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 && (
              <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={handleSubmit}>
              <div className="card-body grid gap-5 p-0">
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Transfer Type Name
                      <span className="text-red-500">*</span>
                    </label>
                    <div className="grow">
                      <Input
                        className="input"
                        type="text"
                        autoComplete="off"
                        value={formField.name}
                        onChange={({ target }) =>
                          setFormField((prev) => ({ ...prev, name: target.value }))
                        }
                      />
                    </div>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Description
                      <span className="text-red-500">*</span>
                    </label>
                    <div className="grow">
                      <Input
                        className="input"
                        type="text"
                        autoComplete="off"
                        value={formField.description}
                        onChange={({ target }) =>
                          setFormField((prev) => ({ ...prev, description: target.value }))
                        }
                      />
                    </div>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Minimum Amount
                    </label>
                    <div className="grow">
                      <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>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Maximum Amount
                    </label>
                    <div className="grow">
                      <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>
                </div>
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Max Transaction per day
                    </label>
                    <div className="grow">
                      <NumericFormat
                        className="input"
                        value={formField.max_transaction_per_day}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            max_transaction_per_day: values.floatValue || 0
                          }));
                        }}
                        placeholder="Enter Max Transaction Per Day"
                      />
                    </div>
                  </div>
                </div>
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      From Account
                      <span className="text-red-500">*</span>
                    </label>
                    <div className="grow">
                      <Select
                        value={formField.wallet_origin}
                        onValueChange={(wallet_origin) =>
                          setFormField((prev) => ({ ...prev, wallet_origin }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select Wallet" />
                        </SelectTrigger>
                        <SelectContent>
                          {wallets.map((wallet, idx) => (
                            <SelectItem value={wallet.id} key={wallet.name}>
                              {wallet.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      To Account
                      <span className="text-red-500">*</span>
                    </label>
                    <div className="grow">
                      <Select
                        value={formField.wallet_destination}
                        onValueChange={(wallet_destination) =>
                          setFormField((prev) => ({ ...prev, wallet_destination }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select Wallet" />
                        </SelectTrigger>
                        <SelectContent>
                          {wallets.map((wallet, idx) => (
                            <SelectItem value={wallet.id} key={wallet.id}>
                              {wallet.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Status Transaction Type
                      <span className="text-red-500"> *</span>
                    </label>

                    <div className="grow">
                      <Select
                        value={formField.type}
                        onValueChange={(value) =>
                          setFormField((prev) => ({ ...prev, type: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="D">Disbursement </SelectItem>
                          <SelectItem value="O">Other </SelectItem>
                          <SelectItem value="CA">Change Group Emoney Customer to Agent </SelectItem>
                          <SelectItem value="AC">Change Group Emoney Agent to Customer </SelectItem>
                          <SelectItem value="PA">Change Group Point Agent to Customer </SelectItem>
                          <SelectItem value="PC">Change Group Point Customer to Agent</SelectItem>
                          <SelectItem value="CE">Return Customer Emoney </SelectItem>
                          <SelectItem value="AD">Return Agent Deposit </SelectItem>
                          <SelectItem value="AM">Return Agent Merchant </SelectItem>
                          <SelectItem value="AE">Return Agent Emoney </SelectItem>
                          <SelectItem value="R">Reward Point </SelectItem>
                          <SelectItem value="TE">Top Up Escrow </SelectItem>
                          <SelectItem value="TM">Top Up Master Agent </SelectItem>
                          <SelectItem value="TA">Top Up Agent </SelectItem>

                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Status Approval
                      <span className="text-red-500">*</span>
                    </label>

                    <div className="grow">
                      <Select
                        value={formField.status_approval}
                        onValueChange={(value) =>
                          setFormField((prev) => ({ ...prev, status_approval: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="Y">Yes</SelectItem>
                          <SelectItem value="N">No</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Status
                      <span className="text-red-500"> *</span>
                    </label>

                    <div className="grow">
                      <Select
                        value={formField.status}
                        onValueChange={(value) =>
                          setFormField((prev) => ({ ...prev, status: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="Y">Active</SelectItem>
                          <SelectItem value="N">Inactive</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </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>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
