import { useCallback, useEffect, useRef, useState } from 'react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { NumericFormat } from 'react-number-format';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { useManageTransferTypeContext } from '../hooks/useManageTransferTypeContext';
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 { getAuth } from '@/auth';
import { ManageTransferFeeContextProvider } from '../../transferfee/hooks/ManageTransferFeeContext';
import AddFeeDialog from '../../transferfee/blocks/AddDialog';
import { EditFeeDialog } from '../../transferfee/blocks/EditDialog';
import DeleteFeeDialog from '../../transferfee/blocks/DeleteDialog';
import { Checkbox } from '@/components/ui/checkbox';
import { doSaveLogActivity } from '@/actions/GlobalActions';

const API_URL = apiConfig.service_transaction;
const API_URL_MASTERDATA = 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 PermissionObject {
  id: string;
  name: string;
  description: string;
  status: string;
}

const EditDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showEditDialog, handleEditDialog, selectedTransferType } = useManageTransferTypeContext();
  const { reload } = useDataGrid();
  const [wallets, setWallets] = useState<WalletProps[]>([]);
  const [groups, setGroups] = useState<PermissionObject[]>([]);
  const { GetData, PutData } = useCallApi();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const parsedUser = getAuth()?.user;
  const [customers, setCustomers] = useState<CustomerProps[]>([]);
  const [selectedGroups, setSelectedGroups] = useState<string[]>([]);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  const initialState: {
    name: string;
    description: string;
    wallet_origin: string;
    wallet_destination: string;
    minimum_amount: number;
    maximum_amount: number;
    max_transaction_per_day: number;
    status: string;
    type: string;
    status_approval: string;
    updated_by: string;
    updated_at: string;
    permission: string[];
  } = {
    name: '',
    description: '',
    wallet_origin: '',
    wallet_destination: '',
    minimum_amount: 0,
    maximum_amount: 0,
    max_transaction_per_day: 0,
    status_approval: '',
    type: '',
    status: '',
    permission: [],
    updated_by: '',
    updated_at: ''
  };

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

  const resetForm = () => {
    setFormField(initialState);
    setSelectedGroups([]);
    setAlert({ show: false, message: '' });
  };

  const handleGroupChange = (groupId: string) => {
    setFormField((prevState) => {
      const isSelected = prevState.permission.includes(groupId);

      if (isSelected) {
        return {
          ...prevState,
          permission: prevState.permission.filter((id) => id !== groupId)
        };
      } else {
        return {
          ...prevState,
          permission: [...prevState.permission, groupId]
        };
      }
    });
  };

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

    const missingFields = requiredFields.filter((field) => {
      return (
        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;
    }

    if (formField.permission.length === 0) {
      setAlert({
        show: true,
        message: 'Please select at least one group permission'
      });
      return false;
    }

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

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

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

  const selectedPermissionNames = groups
    .filter((g) => formField.permission.includes(g.id))
    .map((g) => g.name)
    .join(', ');

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

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

    doUpdateTransferType()
      .then((success) => {
        if (success) {
          handleEditDialog(false, null);
          toast.success('Success Update Transfer Type');
          reload();

          const createActivity = {
            module: 'Manage Transfer Type',
            description: `Edit Transfer Type => ${selectedTransferType}`,
            action: 'U'
          };

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

  const doUpdateTransferType = useCallback(async () => {
    try {
      const formDataToSend = {
        ...formField,
        permission: formField.permission.filter((id) => typeof id === 'string')
      };

      const response = await PutData(
        `${API_URL}/transactiontype/update/${selectedTransferType}`,
        formDataToSend
      );

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

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

    const getCustomerList = async () => {
      try {
        const sorting = [{ id: 'id', desc: false }];
        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'
        });

        if (response?.status && response?.data) {
          setCustomers(response.data.list);
        }
      } catch (error) {
        console.error('Error fetching customer', error);
      }
    };

    getCustomerList();
  }, [showEditDialog, GetData]);

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

    const getGroupList = async () => {
      try {
        const response = await GetData(`${API_URL_MASTERDATA}/groups/list`, {
          limit: 100,
          page: 1,
          with_deleted: false,
          order_field: 'name',
          order_direction: 'ASC'
        });

        if (response?.status && response?.data) {
          setGroups(response.data.list);
        }
      } catch (error) {
        console.error('Error fetching groups', error);
      }
    };

    getGroupList();
  }, [showEditDialog, GetData]);

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

    const getWalletList = async () => {
      try {
        const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, {
          limit: 100,
          page: 1,
          with_deleted: false,
          order_field: 'Wallets.name',
          order_direction: 'ASC'
        });

        if (response?.status && response?.data) {
          setWallets(response.data.list);
        }
      } catch (error) {
        console.error('Error fetching wallets', error);
      }
    };

    getWalletList();
  }, [showEditDialog, GetData]);

  useEffect(() => {
    if (!showEditDialog || !selectedTransferType) return;

    const fetchTransactionType = async () => {
      try {
        const response = await GetData(
          `${API_URL}/transactiontype/getdata/${selectedTransferType}`,
          {}
        );
        // console.log(response);
        if (response?.status) {
          let permissionIds: string[] = [];

          if (Array.isArray(response.data.permission)) {
            permissionIds = response.data.permission.map((perm: any) => {
              if (typeof perm === 'object' && perm !== null) {
                return perm.id;
              }
              return perm;
            });
          }

          setFormField((prev) => ({
            ...prev,
            name: response.data.name,
            description: response.data.description,
            wallet_origin: response.data.wallet_origin?.id || '',
            wallet_destination: response.data.wallet_destination?.id || '',
            minimum_amount: response.data.minimum_amount,
            maximum_amount: response.data.maximum_amount,
            max_transaction_per_day: response.data.max_transaction_per_day,
            status_approval: response.data.status_approval,
            type: response.data.type || '',
            status: response.data.status,
            permission: permissionIds
          }));
        }
      } catch (error) {
        console.error('Error fetching transaction type', error);
        setAlert({
          show: true,
          message: 'Failed to load transaction type data'
        });
      }
    };

    const timer = setTimeout(() => {
      fetchTransactionType();
    }, 150);

    return () => clearTimeout(timer);
  }, [showEditDialog, selectedTransferType, GetData]);
  useEffect(() => {
    if (showEditDialog === false) {
      resetForm();
    }
  }, [showEditDialog]);

  return (
    <Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(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 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={() => {
                handleEditDialog(false, null);
                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) => (
                            <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">
                      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) => (
                            <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="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">
                      Groups
                      <span className="text-red-500">*</span>
                    </label>
                    <div className="relative w-full">
                      <Input
                        type="text"
                        placeholder="No groups selected"
                        value={selectedPermissionNames || ''}
                        readOnly
                        className="bg-gray-100 mb-2"
                      />

                      <div className="border rounded-md p-3 max-h-48 overflow-y-auto">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                          {groups.map((group) => (
                            <div key={group.id} className="flex items-center space-x-2">
                              <Checkbox
                                id={`group-${group.id}`}
                                checked={formField.permission.includes(group.id)}
                                onCheckedChange={() => handleGroupChange(group.id)}
                              />
                              <label
                                htmlFor={`group-${group.id}`}
                                className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                              >
                                {group.name}
                              </label>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="flex justify-end pt-2.5 gap-5">
                  <Button variant={'default'} type="submit" disabled={isSubmitting}>
                    {isSubmitting ? 'Saving...' : 'Save Changes'}
                  </Button>
                </div>
              </div>
            </form>
            <ManageTransferFeeContextProvider transactionTypeId={selectedTransferType}>
              <Container>
                <div className="grid gap-5 lg:gap-7.5 mt-5">
                  <DataGridInner />
                </div>
                <AddFeeDialog />
                <DeleteFeeDialog />
                <EditFeeDialog />
              </Container>
            </ManageTransferFeeContextProvider>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export { EditDialog };
