'use client';

import React, {
  useState,
  useCallback,
  useMemo,
  useRef,
  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, Controller, 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 { transformCommissionData } from './operations';
import EligibleCasesList from './EligibleCasesList';
import { Heading } from '@/components/ui/heading';
import { Button } from '@/components/ui/button';
import CommissionCards from '../form-components/CommissionCards';
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 TaxSection, {
  FormDataWithTaxDetails,
} from '@/components/common/TaxSection';
import { FileUploadField } from '../../contracts/forms/FileUploadField';
import { DateMode, validateInputDate } from '@/utils/dateValidation';
import { maskDate } from '@/utils/dateMask';
import { bankAccountDependentPaymentMode } from '../../bonus/sub-agent/constants';
import { Textarea } from '@/components/ui/textarea';
import { useAppToast } from '@/hooks/useAppToast';
import { VCM_M } from '@/constants/typo/submit-alerts';
import { ATTACHMENT_VALIDATION_COMMON } from '@/constants/attachment';

const useFileManager = () => {
  const [filesByIndex, setFilesByIndex] = useState<Record<number, File[]>>({});
  const [dropdownsByIndex, setDropdownsByIndex] = useState<
    Record<number, boolean>
  >({});

  const handleRemoveFile = useCallback(
    (setIndex: number, fileIndex: number) => {
      setFilesByIndex((prev) => {
        const currentFiles = prev[setIndex] || [];
        const updatedFiles = currentFiles.filter(
          (_, index) => index !== fileIndex,
        );
        return { ...prev, [setIndex]: updatedFiles };
      });
    },
    [],
  );

  const handleAddFiles = useCallback((setIndex: number, newFiles: File[]) => {
    setFilesByIndex((prev) => {
      const currentFiles = prev[setIndex] || [];
      const updatedFiles = [...currentFiles, ...newFiles];
      return { ...prev, [setIndex]: updatedFiles };
    });
  }, []);

  const handleSetFiles = useCallback((setIndex: number, files: File[]) => {
    setFilesByIndex((prev) => ({ ...prev, [setIndex]: files }));
  }, []);

  const toggleDropdown = useCallback((setIndex: number) => {
    setDropdownsByIndex((prev) => ({ ...prev, [setIndex]: !prev[setIndex] }));
  }, []);

  const getFiles = useCallback(
    (setIndex: number): File[] => {
      return filesByIndex[setIndex] || [];
    },
    [filesByIndex],
  );

  return {
    filesByIndex,
    dropdownsByIndex,
    handleRemoveFile,
    handleAddFiles,
    handleSetFiles,
    toggleDropdown,
    getFiles,
  };
};

const AddSubAgentCommission: React.FC<AddCommissionContractProps> = ({
  triggerIcon,
  bucket,
  handlePaginatedRecords,
}) => {
  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 [filterEligibleCases, setFilterEligibleCases] = useState<
    UnknownRecord[]
  >([]);

  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,
  });

  // Data states
  const [defaultCountries, setDefaultCountries] = useState<UnknownRecord[]>([]);
  const [institutes, setInstitutes] = useState<UnknownRecord[]>([]);
  const [intakes, setIntakes] = useState<UnknownRecord[]>([]);
  const [commissionSets, setCommissionSets] = useState<any>([]);
  const [commissionInstances, setCommissionInstances] = useState<any>([]);
  const [commissionSetInstances, setCommissionSetInstances] = useState<any>([]);
  const [eligibleCases, setEligibleCases] = useState<UnknownRecord[]>([]);
  const [instanceSelected, setInstanceSelected] = useState<UnknownRecord>({});
  const [associates, setAssociates] = 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 [isNextLoading, setIsNextLoading] = useState(false);

  const otherDeductionRef = useRef<number>(0);

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

  const form = useForm<z.infer<typeof AddSubAgentCommissionSchema>>({
    resolver: zodResolver(AddSubAgentCommissionSchema),
    shouldUnregister: false,
    defaultValues: {
      ...bucket?.crud?.add.schema.default_values,
      tax_details: {
        ...bucket?.crud?.add.schema.default_values?.tax_details,
        net_amount_inr: '0',
        payment_mode_id: 0,
      },
    },
  });

  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],
  );

  const fileManager = useFileManager();
  const fileInputRef = useRef<HTMLInputElement | null>(null);

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

  const handleOnOpen = useCallback(async () => {
    const apiRequests = [globalApiGet(API_ENDPOINTS.VCM.CLIENT_COUNTRIES)];
    resetFormAndState();
    try {
      const [clientCountriesRes] = (await Promise.all(
        apiRequests,
      )) as ApiResponse<UnknownRecord>[];

      setDefaultCountries(extractData(clientCountriesRes));
    } catch (error) {
      console.error('Error loading data:', error);
      setDefaultCountries([]);
    }
  }, [enquiryType]);

  const resetConfig: Record<
    string,
    {
      states?: (() => void)[];
      fields?: string[];
    }
  > = {
    client_from_country_id: {
      states: [
        () => setAssociates([]),
        () => setInstitutes([]),
        () => setIntakes([]),
        () => setCommissionInstances([]),
        () => setCommissionSets([]),
        () => setCommissionSetInstances([]),
      ],
      fields: [
        'visa_service_country_id',
        'associate_id',
        'institute_id',
        'intake_id',
        'applicable_on_id',
        'contract_set_id',
        'commission_instance_id',
      ],
    },

    visa_service_country_id: {
      states: [
        () => setAssociates([]),
        () => setInstitutes([]),
        () => setIntakes([]),
        () => setCommissionInstances([]),
        () => setCommissionSets([]),
        () => setCommissionSetInstances([]),
      ],
      fields: [
        'associate_id',
        'institute_id',
        'intake_id',
        'applicable_on_id',
        'contract_set_id',
        'commission_instance_id',
      ],
    },

    associate_id: {
      states: [
        () => setIntakes([]),
        () => setCommissionInstances([]),
        () => setCommissionSets([]),
        () => setCommissionSetInstances([]),
      ],
      fields: [
        'institute_id',
        'intake_id',
        'applicable_on_id',
        'contract_set_id',
        'commission_instance_id',
      ],
    },

    institute_id: {
      states: [
        () => setIntakes([]),
        () => setCommissionInstances([]),
        () => setCommissionSets([]),
        () => setCommissionSetInstances([]),
      ],
      fields: [
        'intake_id',
        'applicable_on_id',
        'contract_set_id',
        'commission_instance_id',
      ],
    },

    intake_id: {
      states: [
        () => setCommissionInstances([]),
        () => setCommissionSets([]),
        () => setCommissionSetInstances([]),
      ],
      fields: ['applicable_on_id', 'contract_set_id', 'commission_instance_id'],
    },

    applicable_on_id: {
      states: [
        () => setCommissionSets([]),
        () => setCommissionSetInstances([]),
      ],
      fields: ['contract_set_id', 'commission_instance_id'],
    },

    contract_set_id: {
      states: [() => setCommissionSetInstances([])],
      fields: ['commission_instance_id'],
    },

    commission_instance_id: {
      states: [],
      fields: [],
    },
  };

  const handleChildFieldReset = useCallback(
    (type: keyof typeof resetConfig) => {
      const config = resetConfig[type];
      if (!config) return;
      config.states?.forEach((fn) => fn());
      config.fields?.forEach((field) => setValue(field, ''));
      handleSelectedRowsAndCases();
    },
    [],
  );

  const fetchInstitutes = useCallback(async (country_id: string) => {
    setValue('institute_id', '');
    setValue('intake_id', '');
    setValue('commission_instance_id', '');
    setValue('associate_id', '');
    const response = (await globalApiPost(
      API_ENDPOINTS.VC_ENQUIRY.INSTITUTE_LIST,
      {
        country_id,
      },
      false,
    )) as any;

    if (!(response as any)?.success) {
      showError((response as any).errors, 'Intakes does not exists');
    }

    const res = Array.isArray(response?.data) ? response?.data : [];
    setInstitutes(res);
  }, []);

  const fetchAssociates = useCallback(async (country_id: string) => {
    const response = await globalApiPost(API_ENDPOINTS.VCM.ASSOCIATE_LIST, {
      country_id,
      association_type: '3',
      product_id: '8',
    });

    const res = Array.isArray(response) ? response : [];
    setAssociates(res);
  }, []);

  const fetchIntakes = useCallback(
    async (
      clientFromCountryId: string,
      visaServiceCountryId: string,
      instituteId: string,
    ) => {
      setValue('intake_id', '');
      setValue('commission_instance_id', '');
      const response = await globalApiPost(
        API_ENDPOINTS.VC_ENQUIRY.INTAKE_LIST,
        {
          client_from_country_id: Number(clientFromCountryId),
          visa_service_country_id: Number(visaServiceCountryId),
          institute_id: Number(instituteId),
        },
      );

      const res = Array.isArray(response) ? response : [];
      setIntakes(res);
    },
    [],
  );

  const fetchCommissionInstances = useCallback(
    async (
      clientFromCountryId: string,
      visaServiceCountryId: string,
      instituteId: string,
      intakeId: string,
    ) => {
      setValue('applicable_on_id', '');
      setValue('contract_set_id', '');
      setValue('commission_instance_id', '');
      const payload: any = {
        client_from_country_id: Number(clientFromCountryId),
        visa_service_country_id: Number(visaServiceCountryId),
        institute_id: Number(instituteId),
        associate_id: Number(getValues('associate_id') ?? 0),
        intake_id: Number(intakeId),
        association_type: Number(3),
      };

      const response = (await globalApiPost(
        API_ENDPOINTS.VC_ENQUIRY.INSTANCE_LIST,
        payload,
        false,
      )) as any;
      if (!(response as any)?.success) {
        showError(
          (response as any).errors,
          'Commission Instance does not exists',
        );
      }

      const res = Array.isArray(response.data) ? response.data : [];
      const formattedCommissionInstances = transformCommissionData(res);
      setCommissionInstances(formattedCommissionInstances);
      setCommissionSets([]);
      setCommissionSetInstances([]);
    },
    [],
  );

  const handleApplicableOnChange = useCallback(
    (applicable_on_id: string) => {
      setValue('contract_set_id', '');
      setValue('commission_instance_id', '');
      const selectedInstance = commissionInstances.find(
        (instance: any) =>
          String(instance.applicable_on_id) === applicable_on_id,
      );
      const sets: UnknownRecord[] = [];
      if (selectedInstance && selectedInstance.sets) {
        selectedInstance.sets.forEach((set: any) => {
          sets.push({ id: set.contract_set_id, name: set.set_name });
        });
        setCommissionSets(sets);
      } else {
        setCommissionSets(sets);
      }
      setCommissionSetInstances([]);
    },
    [commissionInstances],
  );

  const handleSetOnChange = useCallback(
    (set_id: string) => {
      setValue('commission_instance_id', '');
      const instances = findInstancesByContractSetId(
        commissionInstances,
        Number(set_id),
      );
      const formattedInstances = instances.map(
        (instance: any, index: number) => ({
          id: instance.id,
          name: `Instance ${index + 1}`,
          commission_amount: instance.commission_amount,
          commission_percentage: instance.commission_percentage,
          commission_type: instance.commission_type,
          currency: instance.currency,
          instance_no: index + 1,
        }),
      );
      setCommissionSetInstances(formattedInstances);
    },
    [commissionInstances],
  );

  const findInstancesByContractSetId = (
    data: UnknownRecord[],
    contractSetId: number,
  ) => {
    for (const group of data) {
      for (const set of group.sets) {
        if (set.contract_set_id === contractSetId) {
          return set.instances;
        }
      }
    }
    return [];
  };

  const handleSetInstanceOnChange = useCallback(async (instanceId: string) => {
    const response = (await globalApiPost(
      API_ENDPOINTS.VC_ENQUIRY.CASE_LIST,
      {
        commission_instance_id: Number(instanceId),
        client_from_country_id: Number(getValues('client_from_country_id')),
        visa_service_country_id: Number(getValues('visa_service_country_id')),
        institute_id: Number(getValues('institute_id') ?? 0),
        intake_id: Number(getValues('intake_id')),
        associate_id: Number(getValues('associate_id') ?? 0),
        association_type: 3,
        applicable_on_id: Number(getValues('applicable_on_id') ?? 0),
        contract_set_id: Number(getValues('contract_set_id') ?? 0),
      },
      false,
    )) as any;
    if (!(response as any)?.success) {
      showError((response as any).errors, 'Case does not exists');
    }
    const res = Array.isArray(response.data) ? response.data : [];

    setEligibleCases(res);
  }, []);

  const handleSelectedRowsAndCases = useCallback(() => {
    setSelectedRows([]);
    setEligibleCases([]);
  }, []);

  const handleStepOneTitles = useCallback(
    (key: string, value: UnknownRecord) => {
      setNextStepValues((prev) => ({ ...prev, [key]: value }));
    },
    [getValues],
  );

  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 === 3) {
        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));

          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;
          }
        } 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);
          setNetAmount(netAmount);
          setAmountAfterTax(netAmount);
          setValue('tax_details.net_amount_inr', netAmount.toString());

          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 case data:', error);
      }
      setIsNextLoading(false);
    },
    [trigger, clearErrors, form, setStep],
  );

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

    otherDeductionRef.current = deductionValue;
    setOtherDeduction(deductionValue);

    const finalAmount = parseFloat((afterTax - deductionValue).toFixed(2));
    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 handleSetAmountAfterTax = (value: string | number) => {
    const parsed = parseFloat(String(value)) || 0;
    setAmountAfterTax(parsed);

    const deduction = otherDeductionRef.current;
    const net = parseFloat((parsed - deduction).toFixed(2));
    setNetAmount(net);
    setValue('tax_details.net_amount_inr', net.toString());
  };

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

        if (parseFloat(taxDetails.net_amount_inr || '0') < 0) {
          setError('tax_details.net_amount_inr', {
            type: 'manual',
            message: 'Total Amount in INR cannot be negative.',
          });
          return;
        }

        if (
          taxDetails.payment_date === '' ||
          taxDetails.payment_date === null
        ) {
          setError('tax_details.payment_date', {
            type: 'manual',
            message: 'Payment Date is required.',
          });
          return;
        }

        if (
          taxDetails.payment_mode_id === '' ||
          taxDetails.payment_mode_id === null
        ) {
          setError('tax_details.payment_mode_id', {
            type: 'manual',
            message: 'Payment Mode is required.',
          });
          return;
        }

        if (taxDetails.payment_mode_id !== '1') {
          if (
            taxDetails.bank_account_id === '' ||
            taxDetails.bank_account_id === null
          ) {
            setError('tax_details.bank_account_id', {
              type: 'manual',
              message: 'Bank Account is required.',
            });
            return;
          }
          if (
            taxDetails.transaction_id === '' ||
            taxDetails.transaction_id === null
          ) {
            setError('tax_details.transaction_id', {
              type: 'manual',
              message: 'Transaction ID is required.',
            });
            return;
          }
        }

        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 = Number(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;
        if (!taxDetails.net_amount_inr || taxDetails.net_amount_inr <= 0) {
          setError(`tax_details.net_amount_inr`, {
            type: 'required',
            message: 'Net Amount in INR is must be greater than 0',
          });
          hasError = true;
        }

        if (!taxDetails.payment_mode_id || taxDetails.payment_mode_id == 1) {
          taxDetails.from_bank_account_id = 0;
          taxDetails.to_bank_account_id = 0;
          taxDetails.transaction_id = '';
        }

        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,
          other_deductions: taxDetails?.other_deductions || 0,
          deduction_reason: taxDetails?.deduction_reason || '',
          payment_mode_id: String(taxDetails?.payment_mode_id),
          remarks: taxDetails?.remarks || '',
        };

        const formDataBuilt = objectToFormData(postData);
        const attachmentFiles =
          fileManager.getFiles('attachment_files' as any) || [];

        attachmentFiles.forEach((file: File) => {
          formDataBuilt.append('attachment_files', file, file.name);
        });

        const res = await globalApiFormDataPost(
          API_ENDPOINTS.SUB_AGENT_COMMISSION.ADD,
          formDataBuilt,
        );

        fileManager.handleSetFiles('attachment_files' as any, []);

        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, fileManager, getValues],
  );

  const resetFormAndState = useCallback(() => {
    form.reset({
      attachment_files: [],
    });
    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, fileManager]);

  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}>
      <DialogTrigger
        onClick={() => {
          handleOnOpen();
          setIsDialogOpen(true);
        }}
        asChild
      >
        {triggerIcon || (
          <Text
            title="Add"
            className="add-icn wo-fts-filter-bts flex justify-content items-start"
          >
            <span>
              <CommonImage
                src="/main/add-icn.webp"
                width={20}
                height={20}
                alt="Add"
                classname="add-icon"
              />
            </span>{' '}
            Add
          </Text>
        )}
      </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">
          Add Sub-Agent Commission
        </DialogTitle>
        <DialogDescription>{''}</DialogDescription>
        <DialogClose asChild>
          <button
            onClick={() => {
              setIsDialogOpen(false);
              // Clear files when dialog closes
              fileManager.handleSetFiles('attachment_files' as any, []);
            }}
            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">
                  <>
                    <FormField
                      control={control}
                      name="client_from_country_id"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Client Country"
                          placeholder="Choose Client Country"
                          options={defaultCountries.map((item: any) => ({
                            id: item.id,
                            name: item.name,
                          }))}
                          isOpen={dropdownStates.client_from_country_id}
                          onOpenChange={() =>
                            toggleDropdown('client_from_country_id')
                          }
                          onSelect={(value) => {
                            field.onChange(String(value));
                            handleChildFieldReset('client_from_country_id');
                            handleStepOneTitles('client_from_country_id', {
                              title: 'Client Country',
                              value:
                                defaultCountries.find(
                                  (country: any) =>
                                    String(country.id) === String(value),
                                )?.name || '',
                            });
                            clearErrors('client_from_country_id');
                            setDropdownStates((prev) => ({
                              ...prev,
                              client_from_country_id: false,
                            }));
                          }}
                          required
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="visa_service_country_id"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Visa Service Country"
                          placeholder="Choose Visa Service Country"
                          options={defaultCountries.map((item: any) => ({
                            id: item.id,
                            name: item.name,
                          }))}
                          isOpen={dropdownStates.visa_service_country_id}
                          onOpenChange={() =>
                            toggleDropdown('visa_service_country_id')
                          }
                          onSelect={(value) => {
                            field.onChange(String(value));
                            handleChildFieldReset('visa_service_country_id');
                            fetchInstitutes(String(value));
                            fetchAssociates(String(value));
                            handleStepOneTitles('visa_service_country_id', {
                              title: 'Visa Service Country',
                              value:
                                defaultCountries.find(
                                  (country: any) =>
                                    String(country.id) === String(value),
                                )?.name || '',
                            });
                            clearErrors('visa_service_country_id');
                            setDropdownStates((prev) => ({
                              ...prev,
                              visa_service_country_id: false,
                            }));
                          }}
                          required
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="associate_id"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Associate"
                          placeholder="Choose Associate"
                          options={associates.map((item: any) => ({
                            id: item.id,
                            name: item.name,
                          }))}
                          isOpen={dropdownStates.associate_id}
                          onOpenChange={() => toggleDropdown('associate_id')}
                          onSelect={(value) => {
                            field.onChange(String(value));
                            handleChildFieldReset('associate_id');
                            handleStepOneTitles('associate_id', {
                              title: 'Associate',
                              value:
                                associates.find(
                                  (associate: any) =>
                                    String(associate.id) === String(value),
                                )?.name || '',
                            });
                            clearErrors('associate_id');
                            setDropdownStates((prev) => ({
                              ...prev,
                              associate_id: false,
                            }));
                          }}
                          required
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="institute_id"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Institute"
                          placeholder="Choose Institute"
                          options={institutes.map((item: any) => ({
                            id: String(item.id),
                            name: item.name,
                          }))}
                          isOpen={dropdownStates.institute_id}
                          onOpenChange={() => toggleDropdown('institute_id')}
                          onSelect={(value) => {
                            field.onChange(String(value));
                            handleChildFieldReset('institute_id');
                            fetchIntakes(
                              getValues('client_from_country_id'),
                              getValues('visa_service_country_id'),
                              String(value),
                            );
                            handleStepOneTitles('institute_id', {
                              title: 'Institute',
                              value:
                                institutes.find(
                                  (institute: any) =>
                                    String(institute.id) === String(value),
                                )?.name || '',
                            });
                            clearErrors('institute_id');
                            setDropdownStates((prev) => ({
                              ...prev,
                              institute_id: false,
                            }));
                          }}
                          required
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="intake_id"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Intake"
                          placeholder="Choose Intake"
                          options={intakes.map((item: any) => ({
                            id: item.id,
                            name: item.name,
                          }))}
                          isOpen={dropdownStates.intake_id}
                          onOpenChange={() => toggleDropdown('intake_id')}
                          onSelect={(value) => {
                            field.onChange(String(value));
                            handleChildFieldReset('intake_id');
                            fetchCommissionInstances(
                              getValues('client_from_country_id'),
                              getValues('visa_service_country_id'),
                              getValues('institute_id'),
                              String(value),
                            );
                            handleStepOneTitles('intake_id', {
                              title: 'Intake',
                              value:
                                intakes.find(
                                  (intake: any) =>
                                    String(intake.id) === String(value),
                                )?.name || '',
                            });
                            clearErrors('intake_id');
                            setDropdownStates((prev) => ({
                              ...prev,
                              intake_id: false,
                            }));
                          }}
                          required
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="applicable_on_id"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Applicable On"
                          placeholder="Choose Applicable On"
                          options={commissionInstances.map((item: any) => ({
                            id: item.applicable_on_id,
                            name: item.title,
                          }))}
                          isOpen={dropdownStates.applicable_on_id}
                          onOpenChange={() =>
                            toggleDropdown('applicable_on_id')
                          }
                          onSelect={(value) => {
                            field.onChange(String(value));
                            handleChildFieldReset('applicable_on_id');
                            handleApplicableOnChange(String(value));
                            handleStepOneTitles('applicable_on_id', {
                              title: 'Applicable On',
                              value:
                                commissionInstances.find(
                                  (appOn: any) =>
                                    String(appOn.applicable_on_id) ===
                                    String(value),
                                )?.title || '',
                            });
                            clearErrors('applicable_on_id');
                            setDropdownStates((prev) => ({
                              ...prev,
                              applicable_on_id: false,
                            }));
                          }}
                          required
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="contract_set_id"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Contract Set"
                          placeholder="Choose Contract Set"
                          options={commissionSets.map((item: any) => ({
                            id: item.id,
                            name: item.name,
                          }))}
                          isOpen={dropdownStates.contract_set_id}
                          onOpenChange={() => toggleDropdown('contract_set_id')}
                          onSelect={(value) => {
                            field.onChange(String(value));
                            handleChildFieldReset('contract_set_id');
                            handleStepOneTitles('contract_set_id', {
                              title: 'Contract Set',
                              value:
                                commissionSets.find(
                                  (set: any) =>
                                    String(set.id) === String(value),
                                )?.name || '',
                            });
                            clearErrors('contract_set_id');
                            handleSetOnChange(String(value));
                            setDropdownStates((prev) => ({
                              ...prev,
                              contract_set_id: false,
                            }));
                          }}
                          required
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="commission_instance_id"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Commission Instance"
                          placeholder="Choose Commission Instance"
                          options={commissionSetInstances.map((item: any) => ({
                            id: item.id,
                            name: item.name,
                          }))}
                          isOpen={dropdownStates.commission_instance_id}
                          onOpenChange={() =>
                            toggleDropdown('commission_instance_id')
                          }
                          onSelect={(value) => {
                            field.onChange(String(value));
                            handleChildFieldReset('commission_instance_id');
                            handleStepOneTitles('commission_instance_id', {
                              title: 'Commission Instance',
                              value:
                                commissionSetInstances.find(
                                  (instance: any) =>
                                    String(instance.id) === String(value),
                                )?.name || '',
                            });
                            handleSetInstanceOnChange(String(value));
                            setInstanceSelected(
                              commissionSetInstances.find(
                                (instance: any) =>
                                  String(instance.id) === String(value),
                              ) || {},
                            );
                            clearErrors('commission_instance_id');
                            setDropdownStates((prev) => ({
                              ...prev,
                              commission_instance_id: false,
                            }));
                          }}
                          required
                        />
                      )}
                    />
                  </>
                  {eligibleCases.length > 0 && (
                    <Text className="container-widget mx-auto">
                      <Text className="wo-favorite-table box wo-table-ui-scroller">
                        <Text className="wo-box-header flex justify-between gap-5">
                          <Text className="wo-box-header-left">
                            <Heading
                              level="h3"
                              className="box-title text-primary"
                            >
                              Select Eligible Cases
                            </Heading>
                          </Text>
                        </Text>
                        <Text className="p-1 w-full overflow-auto table-responsive table-container mt-2">
                          <EligibleCasesList
                            tableData={eligibleCases}
                            selectedRows={selectedRows}
                            setSelectedRows={setSelectedRows}
                            filterEligibleCases={filterEligibleCases}
                            setFilterEligibleCases={setFilterEligibleCases}
                          />
                        </Text>
                      </Text>
                    </Text>
                  )}
                </Text>
              )}
              {step === 2 && (
                <>
                  <Text className="flex flex-wrap p-2 form-mid mt-0">
                    <StepOneInfo titles={nextStepValues} />
                    <CommissionCards
                      instanceSelected={instanceSelected}
                      control={control}
                      records={eligibleCases}
                      enquiryType={enquiryType as string}
                      filterEligibleCases={filterEligibleCases}
                    />
                  </Text>
                </>
              )}
              {step === 3 && (
                <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={{}}
                    totalAmount={totalAmount}
                    amountAfterTax={amountAfterTax}
                    setAmountAfterTax={handleSetAmountAfterTax}
                    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={true}
                      />
                    )}
                  />
                  {!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>

                      <Controller
                        control={control}
                        name="attachment_files"
                        render={({ field }) => {
                          const specificFiles = fileManager.getFiles(
                            'attachment_files' as any,
                          );
                          const dropdownOpen =
                            fileManager.dropdownsByIndex[
                              'attachment_files' as any
                            ] || false;

                          return (
                            <FileUploadField
                              field={field}
                              label={`Transaction Screenshot (Allowed: ${ATTACHMENT_VALIDATION_COMMON.label})`}
                              acceptFileFormat={ATTACHMENT_VALIDATION_COMMON.allowedTypes
                                .map((t) => `.${t}`)
                                .join(',')}
                              maxFiles={ATTACHMENT_VALIDATION_COMMON.maxFiles}
                              maxFileSize={
                                ATTACHMENT_VALIDATION_COMMON.maxFileSize
                              }
                              acceptFileFormatLabel={
                                ATTACHMENT_VALIDATION_COMMON.label
                              }
                              files={specificFiles}
                              onFilesChange={(newFiles: File[]) => {
                                fileManager.handleSetFiles(
                                  'attachment_files' as any,
                                  newFiles,
                                );
                                field.onChange(newFiles);
                              }}
                              dropdownOpen={dropdownOpen}
                              onToggleDropdown={() =>
                                fileManager.toggleDropdown(
                                  'attachment_files' as any,
                                )
                              }
                              onRemoveFile={(fileIndex: number) => {
                                fileManager.handleRemoveFile(
                                  'attachment_files' as any,
                                  fileIndex,
                                );
                                const updatedFiles = specificFiles.filter(
                                  (_: File, index: number) =>
                                    index !== fileIndex,
                                );
                                field.onChange(updatedFiles);
                              }}
                              // fileInputRef={fileInputRef}
                            />
                          );
                        }}
                      />
                    </>
                  )}
                  <div className="flex flex-row items-start 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-start footer-modal text-right gap-2 m-0 pr-4 p-2`}
              >
                {selectedRows.length > 0 && (
                  <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-start 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={() => setStep(1)}
                >
                  Previous
                </Button>
                {selectedRows.length > 0 && (
                  <Button
                    type="button"
                    className="m-0 filter-search-btn tracking-wider w-40 primary-button"
                    disabled={isNextLoading}
                    onClick={() => handleNext(3)}
                  >
                    {isNextLoading && (
                      <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                    )}
                    {isNextLoading ? 'Processing...' : 'Next'}
                  </Button>
                )}
              </div>
            )}
            {step === 3 && (
              <div
                className={`modal-footer flex justify-end items-start 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(2)}
                >
                  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 AddSubAgentCommission;
