'use client';

import React, { useState, useCallback, useMemo, useRef } 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,
  BucketProp,
  HandlePaginatedRecords,
} from '@/types';
import {
  globalApiFormDataPost,
  globalApiGet,
  globalApiPost,
} from '@/services/global/globalApiCalls';
import { Button } from '@/components/ui/button';
import { Input } from '../../ui/input';
import TaxSection, { FormDataWithTaxDetails } from '../../common/TaxSection';
import { bankAccountDependentPaymentMode, calculateAmount } from './constants';
import { formatDate } from '@/utils/decorators';
import { DateMode, validateInputDate } from '@/utils/dateValidation';
import { maskDate } from '@/utils/dateMask';
import { SearchableSelect } from '../contracts/forms/SearchableSelect';
import { objectToFormData } from '../contracts/forms/constants';
import { FileUploadField } from '../contracts/forms/FileUploadField';
import { CURRENCY_LIST } from '@/constants';
import { useFileManager } from '@/hooks/useFileManager';
import { C_M } from '@/constants/typo/submit-alerts';
import { useAppToast } from '@/hooks/useAppToast';
import { Textarea } from '@/components/ui/textarea';
import { ATTACHMENT_VALIDATION_COMMON } from '@/constants/attachment';

export type AddCommissionBonusProps = {
  record?: UnknownRecord;
  triggerIcon?: React.ReactNode;
  bucket: BucketProp['bucket'];
  handlePaginatedRecords: HandlePaginatedRecords;
  onSuccess?: () => void;
};

const AddCommissionBonus: React.FC<AddCommissionBonusProps> = ({
  triggerIcon,
  bucket,
  handlePaginatedRecords,
  onSuccess,
}) => {
  const fileManager = useFileManager();
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const { toast } = useToast();
  const { showSuccess, showError } = useAppToast();

  const [isDialogOpen, setIsDialogOpen] = useState(false);

  const [dropdownStates, setDropdownStates] = useState({
    visa_service_country_id: false,
    associate_id: false,
    payment_mode_id: false,
    bank_account_id: false,
    currency: false,
  });

  // Data states
  const [defaultServiceCountries, setDefaultServiceCountries] = useState<
    UnknownRecord[]
  >([]);
  const [defaultAssociates, setDefaultAssociates] = useState<UnknownRecord[]>(
    [],
  );
  const [defaultPaymentModes, setDefaultPaymentModes] = useState<
    UnknownRecord[]
  >([]);
  const [defaultBankAccounts, setDefaultBankAccounts] = 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 [totalAmountInr, setTotalAmountInr] = useState<string | number>(0);
  const [conversionRate, setConversionRate] = useState<string | number>(0);

  const AddBonusSchema = bucket?.crud?.add.schema.validator;
  const form = useForm<z.infer<typeof AddBonusSchema>>({
    resolver: zodResolver(AddBonusSchema),
    defaultValues: bucket?.crud?.add.schema.default_values,
  });

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

  const associationType = useMemo(
    () => bucket?.default_params?.association_type,
    [bucket],
  );

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

  const handleOnOpen = useCallback(async () => {
    const extractData = (response: unknown) =>
      Array.isArray(response) ? response : [];
    resetFormAndState();

    const apiRequests = [
      globalApiGet(API_ENDPOINTS.BONUS_RECEIVED.VISA_SERVICE_COUNTRIES),
      globalApiGet(API_ENDPOINTS.BONUS_RECEIVED.PAYMENT_MODE_LIST),
      globalApiGet(API_ENDPOINTS.BONUS_RECEIVED.BANK_ACCOUNT_LIST),
    ];

    try {
      const [serviceCountriesRes, paymentModesRes, bankAccountRes] =
        (await Promise.all(apiRequests)) as ApiResponse<UnknownRecord>[];
      setDefaultServiceCountries(extractData(serviceCountriesRes));
      setDefaultAssociates([]);
      setDefaultPaymentModes(extractData(paymentModesRes));
      setDefaultBankAccounts(extractData(bankAccountRes));
    } catch (error) {
      console.error('Error loading data:', error);
      setDefaultServiceCountries([]);
      setDefaultAssociates([]);
      setDefaultPaymentModes([]);
      setDefaultBankAccounts([]);
    }
  }, []);

  const resetFormAndState = useCallback(() => {
    form.reset({
      attachment_files: [],
    });

    setDefaultServiceCountries([]);
    setDefaultAssociates([]);
    setDefaultPaymentModes([]);
    setDefaultBankAccounts([]);

    setTotalAmountInr('');
    setConversionRate('');
    setTotalAmount('');
    setNetAmount('');
    setAmountAfterTax('');
    setOtherDeduction('');

    fileManager.setFilesByIndex((prev: any) => ({
      ...prev,
      ['attachment_files']: [],
    }));
  }, [form, fileManager]);

  const handleTotalAmountOnChange = () => {
    const conversionRateValue = getValues('conversion_rate') || '0';
    const conversionRateNum = parseFloat(conversionRateValue) || 0;
    convertToInr(conversionRateNum.toString());
  };

  const handleChildValues = useCallback(async () => {
    setValue('bank_account_id', '');
  }, []);

  const handleServiceCountryChange = useCallback(
    async (visaServiceCountryId: string) => {
      setValue('bank_account_id', '');

      const params: UnknownRecord = {
        visa_service_country_id: Number(visaServiceCountryId),
        association_type: Number(associationType),
      };

      try {
        const associates = await globalApiPost<ApiResponse<UnknownRecord[]>>(
          API_ENDPOINTS.BONUS_RECEIVED.ASSOCIATE_LIST,
          params,
        );

        setDefaultAssociates(Array.isArray(associates) ? associates : []);
      } catch (error) {
        console.error('Error loading Associates:', error);
        setDefaultAssociates([]);
      }
    },
    [setValue, form],
  );

  const convertToInr = (amount: string) => {
    const totalAmountValue = getValues('total_amount') || '0';
    const totalAmountNum = parseFloat(totalAmountValue) || 0;
    const convertedAmount = parseFloat(amount) * totalAmountNum;
    const total = parseFloat(String(convertedAmount)) || 0;
    setTotalAmount(total);

    const taxes = getValues('items') as Array<Record<string, any>>;
    let totalTax = 0;

    taxes.forEach((tax, index) => {
      const taxAmount = calculateAmount(tax.tax_per, total);
      totalTax += taxAmount;
      setValue(`items.${index}.tax_amount`, taxAmount as any);
    });

    const afterTax = parseFloat((total - totalTax).toFixed(2));
    setAmountAfterTax(afterTax);

    const deduction = parseFloat(String(otherDeduction)) || 0;
    const net = parseFloat((afterTax - deduction).toFixed(2));

    setNetAmount(net);
    setValue('net_amount_inr', net.toString());
  };

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

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

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

  const onSubmit = useCallback(
    async (data: z.infer<typeof AddBonusSchema>) => {
      try {
        const items = getValues('items') as Array<Record<string, any>>;
        let totalTaxAmount = 0;

        items.forEach((item: Record<string, any>) => {
          totalTaxAmount += parseFloat(item.tax_amount) || 0;
        });
        totalTaxAmount = parseFloat(totalTaxAmount.toFixed(2));
        data.total_tax_amount = String(totalTaxAmount);
        data.association_type = Number(associationType);
        data.visa_service_country_id = Number(data.visa_service_country_id);
        data.associate_id = Number(data.associate_id);
        data.bank_account_id =
          data.payment_mode_id == 1 ? null : Number(data.bank_account_id);
        data.transaction_id =
          data.payment_mode_id == 1 ? '' : String(data.transaction_id);
        const convertedAmount =
          parseFloat(data.conversion_rate) * parseFloat(data.total_amount);
        data.total_amount_inr = String(convertedAmount) || 0;
        data.payment_date = data.payment_date;
        data.conversion_rate = String(getValues('conversion_rate'));

        const submissionData = {
          ...data,
          tax_details: items && items.length > 0 ? JSON.stringify(items) : null,
          other_deductions: String(parseFloat(data.other_deductions) || 0),
          deduction_reason: data.deduction_reason ?? '',
          remarks: data.remarks ?? '',
        };

        const finalPostData = objectToFormData(submissionData);

        // Get the files from form field value (which should be a FileList)
        const attachmentFiles =
          fileManager.filesByIndex['attachment_files' as any] || [];

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

        const response = (await globalApiFormDataPost(
          API_ENDPOINTS.BONUS_RECEIVED.ADD,
          finalPostData,
        )) as UnknownRecord;

        if (!response?.success) {
          showError((response as any).errors, C_M.CREATE_FAILED);
        } else {
          showSuccess(C_M.CREATE_SUCCESS);
          onSuccess?.();
          setIsDialogOpen(false);
          handlePaginatedRecords(1, {});
          resetFormAndState();
        }
      } catch (error) {
        console.error('Submission error:', error);
        showError(error, C_M.SUBMIT_ERROR);
      }
    },
    [handlePaginatedRecords, form, toast, fileManager.filesByIndex],
  );

  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 Commission Bonus -{' '}
          {associationType == 1 ? 'Institute' : 'Master Agent'}
        </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={handleSubmit(onSubmit, (errors) => {
              console.log('Validation failed:', errors);
            })}
            encType="multipart/form-data"
          >
            <Text className="main-scroll-widget">
              <Text className="flex flex-wrap p-2 form-mid mt-0">
                <>
                  <FormField
                    control={control}
                    name="visa_service_country_id"
                    render={({ field }) => (
                      <SearchableSelect
                        field={field}
                        label="Visa Service Country"
                        placeholder="Choose Visa Service Country"
                        options={defaultServiceCountries.map((item: any) => ({
                          id: String(item.id),
                          name: item.name,
                        }))}
                        isOpen={dropdownStates.visa_service_country_id}
                        onOpenChange={() =>
                          toggleDropdown('visa_service_country_id')
                        }
                        onSelect={(value) => {
                          field.onChange(String(value));
                          handleChildValues();
                          clearErrors('visa_service_country_id');
                          setDropdownStates((prev) => ({
                            ...prev,
                            visa_service_country_id: false,
                          }));
                          handleServiceCountryChange(String(value));
                        }}
                        required
                      />
                    )}
                  />

                  <FormField
                    control={control}
                    name="associate_id"
                    render={({ field }) => (
                      <SearchableSelect
                        field={field}
                        label={
                          Number(associationType) === 1
                            ? 'Institute'
                            : 'Master Agent'
                        }
                        placeholder={`Choose ${Number(associationType) === 1 ? 'Institute' : 'Master Agent'}`}
                        options={defaultAssociates.map((item: any) => ({
                          id: String(item.id),
                          name: item.name,
                        }))}
                        isOpen={dropdownStates.associate_id}
                        onOpenChange={() => toggleDropdown('associate_id')}
                        onSelect={(value) => {
                          field.onChange(String(value));
                          handleChildValues();
                          clearErrors('associate_id');
                          setDropdownStates((prev) => ({
                            ...prev,
                            associate_id: false,
                          }));
                        }}
                        required
                      />
                    )}
                  />

                  <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>
                      Total Amount
                    </label>
                    <FormField
                      control={control}
                      name="total_amount"
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <div className="country-tag">{}</div>
                          <FormControl className="input-pl-50">
                            <Input
                              type="text"
                              placeholder="Enter Total Amount"
                              maxLength={16}
                              value={String(field.value || '')}
                              onBlur={field.onBlur}
                              className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                              onChange={(e) => {
                                const value = String(e.target.value);
                                if (/^\d*\.?\d*$/.test(value)) {
                                  field.onChange(value);
                                  handleTotalAmountOnChange();
                                }
                              }}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <FormField
                    control={control}
                    name="currency"
                    render={({ field }) => (
                      <SearchableSelect
                        field={field}
                        label="Currency"
                        placeholder="Choose Currency"
                        options={CURRENCY_LIST.map((item: any) => ({
                          id: String(item.id),
                          name: item.name,
                        }))}
                        isOpen={dropdownStates.currency}
                        onOpenChange={() => toggleDropdown('currency')}
                        onSelect={(value) => {
                          field.onChange(String(value));
                          handleChildValues();
                          clearErrors('currency');
                          setDropdownStates((prev) => ({
                            ...prev,
                            currency: false,
                          }));
                        }}
                        required
                      />
                    )}
                  />

                  <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>
                      Conversion Rate
                    </label>
                    <FormField
                      control={control}
                      name="conversion_rate"
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <div className="country-tag">{}</div>
                          <FormControl className="input-pl-50">
                            <Input
                              type="text"
                              placeholder="Enter Conversion Rate"
                              maxLength={7}
                              value={String(field.value || '')}
                              onChange={(e) => {
                                const value = String(e.target.value);
                                if (/^\d*\.?\d*$/.test(value)) {
                                  field.onChange(value);
                                  convertToInr(value);
                                }
                              }}
                              onBlur={field.onBlur}
                              className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                            />
                          </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>
                      Converted to INR
                    </label>
                    <FormField
                      control={control}
                      name="total_amount_inr"
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <FormControl className="input-pl-50">
                            <Input
                              type="text"
                              readOnly
                              placeholder="Total Amount INR"
                              value={String(totalAmount || '')}
                              onChange={(e) => {
                                field.onChange(String(e.target.value));
                              }}
                              onBlur={field.onBlur}
                              className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <TaxSection
                    control={
                      form.control as unknown as Control<FormDataWithTaxDetails>
                    }
                    name="items"
                    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="other_deductions"
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <FormControl>
                            <Input
                              type="text"
                              placeholder="Enter Other Deductions"
                              maxLength={16}
                              value={String(field.value || '')}
                              onBlur={field.onBlur}
                              className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                              onChange={(e) => {
                                const value = String(e.target.value);
                                if (/^\d*\.?\d*$/.test(value)) {
                                  field.onChange(value);
                                  handleOtherDeductionOnChange(String(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="deduction_reason"
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <FormControl>
                            <Input
                              {...field}
                              value={field.value ?? ''}
                              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"
                            />
                          </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="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={netAmount ?? ''}
                              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="payment_date"
                      rules={{ required: 'Payment date is required' }}
                      render={({ field }) => (
                        <FormItem className="space-y-2 w-full rounded-full">
                          <FormControl>
                            <Input
                              {...field}
                              value={field.value ?? ''}
                              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"
                              onChange={(e) => {
                                const maskedValue = maskDate(e.target.value);
                                field.onChange(maskedValue);
                                const error = validateInputDate(
                                  maskedValue,
                                  DateMode.PAST_CURRENT,
                                );
                                if (error) {
                                  setError('payment_date', { message: error });
                                } else {
                                  clearErrors('payment_date');
                                }
                              }}
                              onBlur={(e) => {
                                const value = e.target.value;
                                const error = validateInputDate(
                                  value,
                                  DateMode.PAST_CURRENT,
                                );
                                if (error) {
                                  setError('payment_date', { message: error });
                                } else {
                                  clearErrors('payment_date');
                                }
                              }}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <FormField
                    control={control}
                    name="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) => {
                          clearErrors('payment_mode_id');
                          setPaymentMode(Number(value));
                          setDropdownStates((prev) => ({
                            ...prev,
                            payment_mode_id: false,
                          }));
                        }}
                        required
                      />
                    )}
                  />
                  {!bankAccountDependentPaymentMode.includes(paymentMode) && (
                    <>
                      <FormField
                        control={control}
                        name="bank_account_id"
                        render={({ field }) => (
                          <SearchableSelect
                            field={field}
                            label="Bank Account"
                            placeholder="Choose Bank Account"
                            options={defaultBankAccounts.map((item: any) => ({
                              id: String(item.id),
                              name: item.name,
                            }))}
                            isOpen={dropdownStates.bank_account_id}
                            onOpenChange={() =>
                              toggleDropdown('bank_account_id')
                            }
                            onSelect={(value) => {
                              clearErrors('bank_account_id');
                              setDropdownStates((prev) => ({
                                ...prev,
                                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="transaction_id"
                          render={({ field }) => (
                            <FormItem className="space-y-2 w-full rounded-full">
                              <FormControl>
                                <Input
                                  {...field}
                                  value={field.value ?? ''}
                                  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 Transaction ID"
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>

                      <Controller
                        control={control}
                        name="attachment_files"
                        render={({ field }) => {
                          const specificFiles =
                            fileManager.filesByIndex[
                              '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) => {
                                fileManager.setFilesByIndex((prev: any) => ({
                                  ...prev,
                                  ['attachment_files']: newFiles,
                                }));
                                field.onChange(newFiles);
                              }}
                              dropdownOpen={dropdownOpen}
                              onToggleDropdown={() =>
                                fileManager.toggleDropdown(
                                  'attachment_files' as any,
                                )
                              }
                              onRemoveFile={(fileIndex) => {
                                const updatedFiles = specificFiles.filter(
                                  (_: any, index: number) =>
                                    index !== fileIndex,
                                );
                                fileManager.setFilesByIndex((prev: any) => ({
                                  ...prev,
                                  ['attachment_files']: updatedFiles,
                                }));
                                field.onChange(updatedFiles);
                              }}
                              // fileInputRef={fileInputRef}
                            />
                          );
                        }}
                      />
                    </>
                  )}
                </>
              </Text>
              <div className="flex flex-row items-end gap-4 p-4">
                <FormField
                  control={control}
                  name="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 remarks here."
                          value={field.value || ''}
                          onChange={field.onChange}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </div>
            </Text>

            <Text className="modal-footer flex justify-end items-end footer-modal text-right gap-2 m-0 pr-4 p-2">
              <DialogClose asChild>
                <Button
                  type="button"
                  className="m-0 filter-search-btn tracking-wider w-40 primary-button"
                  onClick={() => setIsDialogOpen(false)}
                >
                  Cancel
                </Button>
              </DialogClose>
              <Button
                type="submit"
                disabled={isSubmitting}
                className="m-0 filter-search-btn tracking-wider w-40 primary-button"
              >
                {isSubmitting && (
                  <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                )}
                {isSubmitting ? 'Adding...' : 'Add'}
              </Button>
            </Text>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
};

export default AddCommissionBonus;
