'use client';

import React, { useState, useCallback, useMemo, useEffect } from 'react';
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogTitle,
  DialogDescription,
  DialogClose,
} from '@/components/ui/dialog';
import CommonImage from '@/components/common/CommonImage';
import { Text } from '@/components/ui/text';
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
import { Control, useForm } from 'react-hook-form';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { API_ENDPOINTS } from '@/constants';
import { useToast } from '@/hooks/use-toast';
import { UnknownRecord, ApiResponse } from '@/types';
import {
  globalApiFormDataPost,
  globalApiGet,
  globalApiPost,
} from '@/services/global/globalApiCalls';
import { Button } from '@/components/ui/button';
import StepOneInfo from '../form-components/StepOneInfo';
import { Input } from '@/components/ui/input';
import {
  AddCommissionContractProps,
  objectToFormData,
} from '../../contracts/forms/constants';
import { SearchableSelect } from '../../contracts/forms/SearchableSelect';
import { DateMode, validateInputDate } from '@/utils/dateValidation';
import { maskDate } from '@/utils/dateMask';
import { bankAccountDependentPaymentMode } from '../../bonus/sub-agent/constants';
import { formatDate } from '@/utils/decorators';
import { Textarea } from '@/components/ui/textarea';
import { useAppToast } from '@/hooks/useAppToast';
import { VCM_M } from '@/constants/typo/submit-alerts';
import { transformMultipleSelectOptions } from '@/utils/transformers';
import { getMonthShortName } from '@/utils/formatDate';
import CommissionCards from '../form-components/CommissionCards';
import TaxSection, {
  FormDataWithTaxDetails,
} from '../form-components/TaxSection';

const EditSubAgentCommission: React.FC<AddCommissionContractProps> = ({
  triggerIcon,
  bucket,
  handlePaginatedRecords,
  record,
}) => {
  const { toast } = useToast();
  const { showSuccess, showError } = useAppToast();

  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [step, setStep] = useState<number>(1);
  const [nextStepValues, setNextStepValues] = useState<UnknownRecord[]>([]);
  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [clientCountries, setClientCountries] = useState<any>([]);
  const [taxRecords, setTaxRecords] = useState<any>([]);
  const [isNextLoading, setIsNextLoading] = useState(false);

  const [dropdownStates, setDropdownStates] = useState({
    client_from_country_id: false,
    visa_service_country_id: false,
    institute_id: false,
    intake_id: false,
    commission_instance_id: false,
    invoice_branch_id: false,
    invoice_bank_account_id: false,
    applicable_on_id: false,
    contract_set_id: false,
    associate_id: false,
    payment_mode_id: false,
    from_bank_account_id: false,
    to_bank_account_id: false,
  });

  const getDefaultValues = () => ({
    associate_id: String(record?.associate_id ?? ''),
    net_amount: String(record?.net_amount_inr ?? ''),
    remarks: String(record?.remarks ?? ''),
    items: record?.items ?? [],
    visa_service_country_id: String(record?.visa_service_country_id ?? ''),
    institute_id: String(record?.institute_id ?? ''),
    client_from_country_id: String(record?.client_from_country_id ?? ''),
    intake_id: String(record?.intake_id ?? ''),
    applicable_on_id: String(record?.applicable_on_id ?? ''),
    contract_set_id: String(record?.contract_set_id ?? ''),
    commission_instance_id: String(record?.commission_instance ?? ''),
    invoice_branch_id: String(record?.invoice_branch_id ?? ''),
    tax_details: {
      ...bucket?.crud?.add.schema.default_values?.tax_details,
      other_deductions: String(record?.other_deductions ?? ''),
      deduction_reason: String(record?.deduction_reason ?? ''),
      net_amount_inr: String(record?.net_amount_inr ?? ''),
      payment_date: formatDate(record?.payment_date, 'DD/MM/YYYY'),
      payment_mode_id: String(record?.payment_mode_id ?? ''),
      from_bank_account_id: String(record?.from_bank_account_id ?? ''),
      to_bank_account_id: String(record?.to_bank_account_id ?? ''),
      remarks: String(record?.remarks ?? ''),
      transaction_id: String(record?.transaction_id ?? ''),
    },
  });

  // Data states
  const [defaultCountries, setDefaultCountries] = useState<UnknownRecord[]>([]);

  const [eligibleCases, setEligibleCases] = useState<UnknownRecord[]>([]);
  const [filterEligibleCases, setFilterEligibleCases] = useState<
    UnknownRecord[]
  >([]);
  const [instanceSelected, setInstanceSelected] = useState<UnknownRecord>({});
  const [totalAmount, setTotalAmount] = useState<number | string>(0);
  const [amountAfterTax, setAmountAfterTax] = useState<string | number>(0);
  const [otherDeduction, setOtherDeduction] = useState<string | number>(0);
  const [netAmount, setNetAmount] = useState<string | number>(0);
  const [paymentMode, setPaymentMode] = useState<number>(0);
  const [defaultPaymentModes, setDefaultPaymentModes] = useState<
    UnknownRecord[]
  >([]);
  const [companyBanks, setCompanyBanks] = useState<UnknownRecord[]>([]);
  const [associateBanks, setAssociateBanks] = useState<UnknownRecord[]>([]);

  const EditSubAgentCommissionSchema = bucket?.crud?.add.schema.validator;

  const form = useForm<z.infer<typeof EditSubAgentCommissionSchema>>({
    resolver: zodResolver(EditSubAgentCommissionSchema),
    shouldUnregister: false,
    defaultValues: getDefaultValues(),
  });

  const extractData = (response: unknown) =>
    Array.isArray(response) ? response : [];

  const {
    handleSubmit,
    control,
    formState: { isSubmitting, errors },
    setValue,
    clearErrors,
    getValues,
    setError,
    trigger,
    reset,
  } = form;

  const enquiryType = useMemo(
    () => bucket?.additional_info?.contract_type,
    [bucket],
  );

  // Event handlers
  const toggleDropdown = useCallback((key: keyof typeof dropdownStates) => {
    setDropdownStates((prev) => ({ ...prev, [key]: !prev[key] }));
  }, []);

  const handleOnOpen = useCallback(async () => {
    handleOpenChange(true);
    const apiRequests = [globalApiGet(API_ENDPOINTS.VCM.CLIENT_COUNTRIES)];

    try {
      const [clientCountriesRes] = (await Promise.all(
        apiRequests,
      )) as ApiResponse<UnknownRecord>[];

      setDefaultCountries(extractData(clientCountriesRes));
    } catch (error) {
      console.error('Error loading data:', error);
      setDefaultCountries([]);
    }
    const fetchClientCountries = async () => {
      const response = (await globalApiGet(
        API_ENDPOINTS.VCM.CLIENT_COUNTRIES,
      )) as ApiResponse<UnknownRecord>;
      return Array.isArray(response) ? response : [];
    };
    try {
      const [clientCountriesRes] = await Promise.all([fetchClientCountries()]);

      const extractData = (response: any) =>
        Array.isArray(response) ? response : [];
      setClientCountries(
        transformMultipleSelectOptions(extractData(clientCountriesRes)),
      );
    } catch (error) {
      console.error('Error loading data:', error);
      setClientCountries([]);
    }
  }, [enquiryType]);

  const handleNext = useCallback(
    async (step: number) => {
      setIsNextLoading(true);
      if (step === 2) {
        const elementsToValidate = [
          'client_from_country_id',
          'visa_service_country_id',
          'institute_id',
          'intake_id',
          'applicable_on_id',
          'contract_set_id',
          'commission_instance_id',
          'associate_id',
        ];

        const isValid = await trigger(elementsToValidate);
        if (!isValid) {
          setIsNextLoading(false);
          return;
        }

        clearErrors('items');
      }

      if (step === 2) {
        const apiRequests = [
          globalApiGet(API_ENDPOINTS.SUB_AGENT_BONUS.PAYMENT_MODE_LIST),
          globalApiGet(API_ENDPOINTS.SUB_AGENT_COMMISSION.COMPANY_BANK_LIST),
          globalApiPost(
            API_ENDPOINTS.SUB_AGENT_COMMISSION.ASSOCIATE_BANK_LIST,
            { associate_id: Number(getValues('associate_id')) },
          ),
        ];

        try {
          const [paymentModesRes, companyBanksRes, associateBanks] =
            (await Promise.all(apiRequests)) as ApiResponse<UnknownRecord>[];

          setDefaultPaymentModes(extractData(paymentModesRes));
          setCompanyBanks(extractData(companyBanksRes));
          setAssociateBanks(extractData(associateBanks));
        } catch (error) {
          console.error('Error loading data:', error);
          setDefaultCountries([]);
          setCompanyBanks([]);
          setAssociateBanks([]);
        }

        const caseList = getValues('items') || [];

        if (caseList.length > 0) {
          let netAmount = 0;
          caseList.forEach((item: Record<string, any>) => {
            netAmount += parseFloat(item.commission_amount) || 0;
          });
          netAmount = parseFloat(netAmount.toFixed(2));

          setTotalAmount(netAmount);

          // Calculate tax amount from existing tax records
          const totalTax = (record?.tax_details || []).reduce(
            (sum: number, tax: any) =>
              sum + (parseFloat(String(tax.tax_amount)) || 0),
            0,
          );
          const afterTax = Number(
            (netAmount - totalTax - Number(otherDeduction)).toFixed(2),
          );

          setAmountAfterTax(afterTax);
          setNetAmount(afterTax);

          setValue(
            'tax_details.net_amount_inr',
            String(
              afterTax - (parseFloat(String(record?.other_deductions)) || 0),
            ),
          );
          setValue(
            'tax_details.other_deductions',
            String(record?.other_deductions),
          );

          let hasError = false;

          caseList.forEach((item: Record<string, any>, index: number) => {
            if (!item.tuition_fees || item.tuition_fees <= 0) {
              setError(`items.${index}.tuition_fees`, {
                type: 'required',
                message: 'Commission Received is required',
              });
              hasError = true;
            }

            if (!item.commission_type) {
              setError(`items.${index}.commission_type`, {
                type: 'required',
                message: 'Commission type is required',
              });
              hasError = true;
            }

            if (!item.commission_amount || item.commission_amount <= 0) {
              setError(`items.${index}.commission_amount`, {
                type: 'required',
                message: 'Commission amount is required',
              });
              hasError = true;
            }

            if (
              Number(item.commission_type) === 2 &&
              (!item.commission_percentage || item.commission_percentage <= 0)
            ) {
              setError(`items.${index}.commission_percentage`, {
                type: 'required',
                message: 'Commission percentage is required',
              });
              hasError = true;
            }
          });

          if (hasError) {
            setIsNextLoading(false);
            return;
          }
          clearErrors('items');
        }
      }

      try {
        setStep(step);
      } catch (error) {
        console.error('Error loading campus/study level data:', error);
      }
      setIsNextLoading(false);
    },
    [trigger, clearErrors, form, setStep],
  );

  const resetFormAndState = useCallback(() => {
    form.reset();
    setStep(1);
    setSelectedRows([]);
    setEligibleCases([]);
    setNextStepValues([]);
    setInstanceSelected({});

    setDropdownStates({
      client_from_country_id: false,
      visa_service_country_id: false,
      institute_id: false,
      intake_id: false,
      commission_instance_id: false,
      invoice_branch_id: false,
      invoice_bank_account_id: false,
      applicable_on_id: false,
      contract_set_id: false,
      associate_id: false,
      payment_mode_id: false,
      from_bank_account_id: false,
      to_bank_account_id: false,
    });
  }, [form]);

  const handleOtherDeductionOnChange = async (deduction: number | string) => {
    const deductionValue = parseFloat(String(deduction)) || 0;
    const afterTax = parseFloat(String(amountAfterTax)) || 0;

    const finalAmount = parseFloat((afterTax - deductionValue).toFixed(2));
    setOtherDeduction(deductionValue);
    setNetAmount(finalAmount);
    setValue('tax_details.net_amount_inr', finalAmount.toString());

    if (deductionValue > afterTax) {
      setError('tax_details.other_deductions', {
        type: 'manual',
        message: 'Other deductions cannot exceed the amount after tax',
      });
    } else {
      clearErrors('tax_details.other_deductions');
    }
  };

  const onSubmit = useCallback(
    async (data: z.infer<typeof EditSubAgentCommissionSchema>) => {
      try {
        const items = getValues('items');
        const taxDetails = getValues('tax_details') as any;
        let netAmount = 0;

        items.forEach((item: Record<string, any>) => {
          netAmount += parseFloat(item.commission_amount) || 0;
        });
        netAmount = parseFloat(netAmount.toFixed(2));

        data.currency = items[0]?.tuition_fees_currency;
        data.net_amount = String(netAmount);
        data.association_type = String(3);

        let totalTaxAmount = 0;
        taxDetails?.taxes.forEach((tax: Record<string, any>) => {
          totalTaxAmount += parseFloat(tax.tax_amount) || 0;
        });
        totalTaxAmount = parseFloat(totalTaxAmount.toFixed(2));
        const tta = (data.total_tax_amount =
          totalTaxAmount > 0
            ? parseFloat(totalTaxAmount.toFixed(2))
            : parseFloat(totalTaxAmount.toFixed(2)));

        delete data.total_tax_amount;
        data.id = String(record?.id ?? '');

        taxDetails.payment_mode_id = String(taxDetails?.payment_mode_id);
        if (taxDetails.payment_mode_id === '1') {
          taxDetails.from_bank_account_id = null;
          taxDetails.to_bank_account_id = null;
          taxDetails.transaction_id = null;
        }

        const postData = {
          ...data,
          ...taxDetails,
          total_tax_amount: tta,
          items: items && items.length > 0 ? JSON.stringify(items) : null,
          tax_details:
            taxDetails?.taxes && taxDetails?.taxes.length > 0
              ? JSON.stringify(taxDetails?.taxes)
              : null,
          payment_date: taxDetails?.payment_date,
          deduction_reason: taxDetails?.deduction_reason || null,
          payment_mode_id: String(taxDetails?.payment_mode_id),
          currency: 'INR',
        };

        const res = await globalApiPost(
          API_ENDPOINTS.SUB_AGENT_COMMISSION.UPDATE,
          postData,
          false,
        );

        if ((res as any).success) {
          handlePaginatedRecords(1, {});
          resetFormAndState();
          setIsDialogOpen(false);
          showSuccess(VCM_M.ENQUIRY.SUBMIT);
        } else {
          showError((res as any).errors, VCM_M.ENQUIRY.SUBMIT_ERROR);
        }
      } catch (error) {
        console.error('Submission error:', error);
        showError(error, VCM_M.ENQUIRY.SUBMIT_ERROR);
      }
    },
    [handlePaginatedRecords, reset, toast, getValues],
  );

  const handleDialogOpen = async () => {
    const details = await globalApiPost(
      API_ENDPOINTS.SUB_AGENT_COMMISSION.DETAILS_BY_ID,
      { id: String(record?.id) },
    );

    setEligibleCases(Array.isArray(details) ? details : []);
    setFilterEligibleCases(Array.isArray(details) ? details : []);
  };

  const handleOpenChange = async (open: boolean) => {
    if (open) {
      setTaxRecords(record?.tax_details || []);
      handleDialogOpen();

      const set: UnknownRecord = await globalApiGet(
        `${API_ENDPOINTS.VCM.CONTRACT_SET_DETAILS_BY_ID}/${record?.contract_set_id}`,
      );

      const applicableOnId = record?.applicable_on_id ?? 0;

      const applicableOn: UnknownRecord = await globalApiPost(
        `${API_ENDPOINTS.VCM.CONTRACT_APPLICABLE_ON_BY_ID}`,
        { id: String(applicableOnId), type: '2' },
      );

      let applicableOnIndex = 0;
      if (applicableOn && applicableOnId) {
        applicableOnIndex = applicableOn.findIndex(
          (item: { id: number | string }) =>
            String(item.id) === String(applicableOnId),
        );
      }

      const instance = record?.instance
        ? `Instance ${record?.instance?.instance}`
        : '';

      setNextStepValues([
        { title: 'Client Country', value: record?.client_country?.name },
        { title: 'Visa Service Country', value: record?.visa_country?.name },
        {
          title: 'Associate',
          value: `${record?.associate?.affiliate_name} (${record?.associate?.uid})`,
        },
        {
          title: 'Institute',
          value: `${record?.institute?.institueName} (${record?.institute?.UID})`,
        },
        {
          title: 'Intake',
          value: `${getMonthShortName(record?.intake?.intakemonth, false)}-${record?.intake?.intakeyear}`,
        },
        {
          title: 'Applicable On',
          value: `Applicable On Set - ${applicableOnIndex + 1}`,
        },
        { title: 'Contract Set', value: `${set?.set_name}` },
        {
          title: 'Commission Instance',
          value: instance,
        },
      ]);

      form.reset(getDefaultValues());

      const totalAmountValue = parseFloat(
        String(record?.total_amount_inr || 0),
      );

      const totalTaxValue = parseFloat(String(record?.total_tax_amount || 0));

      const afterTax = Number((totalAmountValue - totalTaxValue).toFixed(2));

      setTotalAmount(totalAmountValue);
      setAmountAfterTax(afterTax);
      setOtherDeduction(Number(record?.other_deductions || 0));
      setNetAmount(Number(record?.net_amount_inr || 0));
      setPaymentMode(record?.payment_mode_id);
      setValue(
        'tax_details.net_amount_inr',
        String(record?.net_amount_inr || 0),
      );
    } else {
      resetFormAndState();

      setEligibleCases([]);
      setFilterEligibleCases([]);
      setTaxRecords([]);
      setNextStepValues([]);

      form.reset();
    }
  };

  useEffect(() => {
    const deduction =
      parseFloat(String(getValues('tax_details.other_deductions') || 0)) || 0;

    setOtherDeduction(deduction);

    const finalAmount = Number(amountAfterTax) - deduction;

    setNetAmount(finalAmount);
    setValue('tax_details.net_amount_inr', finalAmount.toString());
  }, [amountAfterTax]);

  return (
    <Dialog
      open={isDialogOpen}
      onOpenChange={(open) => {
        setIsDialogOpen(open);
        handleOpenChange(open);
      }}
    >
      <DialogTrigger
        onClick={() => {
          handleOnOpen();
          setIsDialogOpen(true);
        }}
        asChild
      >
        {triggerIcon || (
          <Button className="button-action">
            <CommonImage
              src={'/main/edit-icon.png'}
              width={15}
              height={15}
              alt={'Edit Record'}
              classname="info-icon"
            />
          </Button>
        )}
      </DialogTrigger>

      <DialogContent
        aria-describedby={undefined}
        className="modal-common-widget w-full max-w-7xl p-0 m-0 table-modal-settings state-widget"
      >
        <DialogTitle className="p-5 modal-header">
          Edit Sub-Agent Commission
        </DialogTitle>
        <DialogDescription>{''}</DialogDescription>
        <DialogClose asChild>
          <button
            onClick={() => {
              setIsDialogOpen(false);
            }}
            className="dialog-close absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none z-[9]"
            aria-label="Close"
          >
            <CommonImage
              src="/main/cross-arrow.webp"
              width={15}
              height={15}
              alt="Close"
              classname="dialog-close-img"
            />
          </button>
        </DialogClose>
        <VisuallyHidden>
          <DialogTitle>Hidden Title</DialogTitle>
        </VisuallyHidden>

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit, (errors) => {
              console.log('Validation failed:', errors);
            })}
          >
            <Text className="main-scroll-widget">
              {step === 1 && (
                <Text className="flex flex-wrap p-2 form-mid mt-0">
                  <StepOneInfo titles={nextStepValues} />

                  {eligibleCases.length > 0 && (
                    <CommissionCards
                      instanceSelected={{}}
                      control={control}
                      records={eligibleCases}
                      enquiryType={'3'}
                      filterEligibleCases={filterEligibleCases}
                      isEdit={true}
                    />
                  )}
                </Text>
              )}

              {step === 2 && (
                <Text className="flex flex-wrap p-2 form-mid mt-0">
                  <TaxSection
                    control={
                      form.control as unknown as Control<FormDataWithTaxDetails>
                    }
                    name="tax_details.taxes"
                    record={record}
                    totalAmount={totalAmount}
                    amountAfterTax={amountAfterTax}
                    setAmountAfterTax={setAmountAfterTax}
                    otherDeduction={otherDeduction}
                    setNetAmount={setNetAmount}
                  />
                  <div className="space-y-2 w-full md:w-1/2 lg:w-1/4 p-2 relative">
                    <label className="text-sm font-bold">
                      Other Deductions
                    </label>
                    <FormField
                      control={control}
                      name="tax_details.other_deductions"
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <FormControl>
                            <Input
                              {...field}
                              minLength={1}
                              maxLength={13}
                              type="text"
                              className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                              placeholder="Enter Other Deductions"
                              value={String(field.value || '')}
                              onChange={(e) => {
                                const value = String(e.target.value);

                                if (/^\d*\.?\d*$/.test(value)) {
                                  field.onChange(value);
                                  handleOtherDeductionOnChange(value);
                                }
                              }}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <div className="space-y-2 w-full md:w-1/2 lg:w-3/4 p-2 relative">
                    <label className="text-sm font-bold">
                      Deduction Reason
                    </label>
                    <FormField
                      control={control}
                      name="tax_details.deduction_reason"
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <FormControl>
                            <Input
                              {...field}
                              minLength={1}
                              maxLength={500}
                              type="text"
                              className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                              placeholder="Enter Deduction Reason"
                              value={String(field.value || '')}
                              onChange={(e) => {
                                const value = String(e.target.value);
                                field.onChange(value);
                              }}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <div className="space-y-2 w-full md:w-1/2 lg:w-1/4 p-2 relative">
                    <label className="text-sm font-bold">
                      <span className="text-red-600 pl-1">*</span>
                      Net Amount in INR
                    </label>
                    <FormField
                      control={control}
                      name="tax_details.net_amount_inr"
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <FormControl>
                            <Input
                              {...field}
                              minLength={1}
                              maxLength={13}
                              readOnly={true}
                              type="text"
                              value={String(field.value || '')}
                              className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                              placeholder="Enter Net Amount in INR"
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <div className="space-y-2 w-full md:w-1/2 lg:w-1/4 p-2 relative">
                    <label className="text-sm font-bold">
                      <span className="text-red-600 pl-1">*</span>
                      Payment Date
                    </label>
                    <FormField
                      control={control}
                      name="tax_details.payment_date"
                      rules={{ required: 'Payment date is required' }}
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <FormControl>
                            <Input
                              {...field}
                              type="text"
                              inputMode="numeric"
                              maxLength={10}
                              placeholder="DD/MM/YYYY"
                              className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                              value={String(field.value || '')}
                              onChange={(e) => {
                                const maskedValue = maskDate(e.target.value);
                                field.onChange(maskedValue);
                                const error = validateInputDate(
                                  maskedValue,
                                  DateMode.PAST_CURRENT,
                                );
                                if (error) {
                                  setError('tax_details.payment_date', {
                                    message: error,
                                  });
                                } else {
                                  clearErrors('tax_details.payment_date');
                                }
                              }}
                              onBlur={(e) => {
                                const value = e.target.value;
                                const error = validateInputDate(
                                  value,
                                  DateMode.PAST_CURRENT,
                                );
                                if (error) {
                                  setError('tax_details.payment_date', {
                                    message: error,
                                  });
                                } else {
                                  clearErrors('tax_details.payment_date');
                                }
                              }}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <FormField
                    control={control}
                    name="tax_details.payment_mode_id"
                    render={({ field }) => (
                      <SearchableSelect
                        field={field}
                        label="Payment Mode"
                        placeholder="Choose Payment Mode"
                        options={defaultPaymentModes.map((item: any) => ({
                          id: item.id,
                          name: item.name,
                        }))}
                        isOpen={dropdownStates.payment_mode_id}
                        onOpenChange={() => toggleDropdown('payment_mode_id')}
                        onSelect={(value) => {
                          field.onChange(Number(value));
                          setPaymentMode(Number(value));
                          clearErrors('tax_details.payment_mode_id');
                          setDropdownStates((prev) => ({
                            ...prev,
                            payment_mode_id: false,
                          }));
                        }}
                        required
                      />
                    )}
                  />

                  {!bankAccountDependentPaymentMode.includes(paymentMode) && (
                    <>
                      <FormField
                        control={control}
                        name="tax_details.from_bank_account_id"
                        render={({ field }) => (
                          <SearchableSelect
                            field={field}
                            label="Company Bank Account"
                            placeholder="Choose Company Bank Account"
                            options={companyBanks.map((item: any) => ({
                              id: String(item.id),
                              name: item.name,
                            }))}
                            isOpen={dropdownStates.from_bank_account_id}
                            onOpenChange={() =>
                              toggleDropdown('from_bank_account_id')
                            }
                            onSelect={(value) => {
                              field.onChange(String(value)); // Fixed: Add this line
                              clearErrors('tax_details.from_bank_account_id');
                              setDropdownStates((prev) => ({
                                ...prev,
                                from_bank_account_id: false,
                              }));
                            }}
                            required={true}
                          />
                        )}
                      />

                      <FormField
                        control={control}
                        name="tax_details.to_bank_account_id"
                        render={({ field }) => (
                          <SearchableSelect
                            field={field}
                            label="Associate Bank Account"
                            placeholder="Choose Associate Bank Account"
                            options={associateBanks.map((item: any) => ({
                              id: String(item.id),
                              name: item.name,
                            }))}
                            isOpen={dropdownStates.to_bank_account_id}
                            onOpenChange={() =>
                              toggleDropdown('to_bank_account_id')
                            }
                            onSelect={(value) => {
                              field.onChange(String(value)); // Fixed: Add this line
                              clearErrors('tax_details.to_bank_account_id');
                              setDropdownStates((prev) => ({
                                ...prev,
                                to_bank_account_id: false,
                              }));
                            }}
                            required={true}
                          />
                        )}
                      />

                      <div className="space-y-2 w-full md:w-1/2 lg:w-1/4 p-2 relative">
                        <label className="text-sm font-bold">
                          <span className="text-red-600 pl-1">*</span>
                          Transaction ID
                        </label>
                        <FormField
                          control={control}
                          name="tax_details.transaction_id"
                          render={({ field }) => (
                            <FormItem className="space-y-2 w-full rounded-full">
                              <FormControl>
                                <Input
                                  {...field}
                                  minLength={1}
                                  maxLength={500}
                                  type="text"
                                  value={String(field.value || '')}
                                  className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                                  placeholder="Enter Transaction ID"
                                  onChange={(e) => {
                                    const value = String(e.target.value);
                                    field.onChange(value);
                                  }}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>
                    </>
                  )}
                  <div className="flex flex-row items-end gap-4 w-full p-2">
                    <FormField
                      control={control}
                      name="tax_details.remarks"
                      render={({ field }) => (
                        <FormItem className="w-full rounded-full">
                          <FormLabel className="no-error-styles font-bold">
                            Remarks
                          </FormLabel>

                          <FormControl className="input-pl-50">
                            <Textarea
                              rows={4}
                              placeholder="Type received commission remarks here."
                              value={String(field.value || '')}
                              onChange={field.onChange}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  </div>
                </Text>
              )}
            </Text>
            {step === 1 && (
              <div
                className={`modal-footer flex justify-end items-end footer-modal text-right gap-2 m-0 pr-4 p-2`}
              >
                <Button
                  type="button"
                  className="m-0 filter-search-btn tracking-wider w-40 primary-button"
                  disabled={isNextLoading}
                  onClick={() => handleNext(2)}
                >
                  {isNextLoading && (
                    <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                  )}
                  {isNextLoading ? 'Processing...' : 'Next'}
                </Button>
              </div>
            )}
            {step === 2 && (
              <div
                className={`modal-footer flex justify-end items-end footer-modal text-right gap-2 m-0 pr-4 p-2`}
              >
                <Button
                  type="button"
                  className="m-0 filter-search-btn tracking-wider w-40 primary-button"
                  disabled={isSubmitting}
                  onClick={() => setStep(1)}
                >
                  Back
                </Button>
                <Button
                  type="submit"
                  className="m-0 filter-search-btn tracking-wider w-40 primary-button"
                  disabled={isSubmitting}
                >
                  {isSubmitting && (
                    <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                  )}
                  {isSubmitting ? 'Submitting...' : 'Submit'}
                </Button>
              </div>
            )}
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
};

export default EditSubAgentCommission;
