'use client';

import React, {
  useState,
  useRef,
  useCallback,
  useMemo,
  useEffect,
} from 'react';
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogTitle,
  DialogDescription,
  DialogClose,
} from '@/components/ui/dialog';
import CommonImage from '@/components/common/CommonImage';
import { Text } from '@/components/ui/text';
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useForm, useFieldArray, Controller } from 'react-hook-form';
import { Textarea } from '@/components/ui/textarea';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { MultiSelect } from '@/components/ui/multi-select';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { storeCommissionContract } from '@/services/visa-commission/visaCommission';
import {
  ALL_SPECIFIC,
  API_ENDPOINTS,
  COMMISSION_INSTANCE_OPTIONS,
  CURRENCY_LIST,
  STUDENT_CONDITION_LIST,
  VC_ASSOCIATE_TYPES,
  VC_BONUS_TYPE,
  VC_COMMISSION_TYPE,
  VC_HAS_BONUS,
  VC_STUDENTS_DURATION,
} from '@/constants';
import { useToast } from '@/hooks/use-toast';
import { transformMultipleSelectOptions } from '@/utils/transformers';
import { UnknownRecord, ApiResponse, VisaProduct } from '@/types';
import { globalApiGet, globalApiPost } from '@/services/global/globalApiCalls';
import { AddCommissionContractProps, buildFormData } from './constants';
import ApplicableOnSection from '../form-components/edit-commission/ApplicableOnSection';
import StudentRangeFields from '../form-components/edit-commission/StudentRangeFields';
import BonusFields from '../form-components/edit-commission/BonusFields';
import CommissionInstancesSection from '../form-components/edit-commission/CommissionInstancesSection';
import ConditionFields from '../form-components/edit-commission/ConditionFields';
import { FileUploadField } from './FileUploadField';
import { SearchableSelect } from './SearchableSelect';
import { FooterButtons } from './FooterButtons';
import { useFileManager } from '@/hooks/useFileManager';
import { VCM_M } from '@/constants/typo/submit-alerts';
import { useAppToast } from '@/hooks/useAppToast';
import { ATTACHMENT_VALIDATION_CONTRACT } from '@/constants/attachment';

FileUploadField.displayName = 'FileUploadField';

const AddCommissionContract: React.FC<AddCommissionContractProps> = ({
  triggerIcon,
  bucket,
  handlePaginatedRecords,
}) => {
  const { toast } = useToast();
  const { showSuccess, showError } = useAppToast();
  const associateType = useMemo(
    () => bucket?.additional_info?.contract_type,
    [bucket],
  );

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

  const [dropdownStates, setDropdownStates] = useState({
    product: false,
    visaServiceCountries: false,
    associate: false,
    studentCondition: false,
    range: false,
    currency: false,
    campus_condition: false,
    study_level_condition: false,
    course_condition: false,
    institute_id: false,
  });

  const [products, setProducts] = useState<VisaProduct[]>([]);
  const [visaServiceCountries, setVisaServiceCountries] = useState<
    UnknownRecord[]
  >([]);
  const [associates, setAssociates] = useState<UnknownRecord[]>([]);
  const [campuses, setCampuses] = useState<UnknownRecord[]>([]);
  const [studyLevels, setStudyLevels] = useState<UnknownRecord[]>([]);
  const [institutes, setInstitutes] = useState<UnknownRecord[]>([]);
  const [clientCountries, setClientCountries] = useState<any>([]);
  const [courses, setCourses] = useState<any>([]);

  const [isRange, setIsRange] = useState<boolean>(false);
  const [noOfInstances, setNoOfInstances] = useState<Record<string, number>>(
    {},
  );

  const [hasBonusByIndex, setHasBonusByIndex] = useState<
    Record<string, boolean>
  >({});
  const [isNextLoading, setIsNextLoading] = useState(false);

  const handleHasBonusChange = useCallback(
    (applicableIndex: number, setIndex: number, value: string) => {
      const key = `${applicableIndex}-${setIndex}`;
      setHasBonusByIndex((prev) => ({ ...prev, [key]: value === '1' }));
    },
    [],
  );

  const [campusCondition, setCampusCondition] = useState<string>('');
  const [studyLevelCondition, setStudyLevelCondition] = useState<string>('');
  const [courseCondition, setCourseCondition] = useState<string>('');

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

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

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

  const {
    fields: applicableSets,
    append: appendApplicableSet,
    remove: removeApplicableSet,
  } = useFieldArray({
    control,
    name: 'applicable_sets',
  });

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

  const contractTypeLabel = useMemo(
    () => (contractType ? VC_ASSOCIATE_TYPES[contractType as string] : ''),
    [contractType],
  );

  const validateAllSetsInApplicableSet = useCallback(
    async (applicableIndex: number): Promise<boolean> => {
      const sets = getValues(`applicable_sets.${applicableIndex}.sets`);

      const fieldsToValidate: string[] = [
        `applicable_sets.${applicableIndex}.applicable_campuses`,
        `applicable_sets.${applicableIndex}.applicable_study_levels`,
        `applicable_sets.${applicableIndex}.applicable_courses`,
        `applicable_sets.${applicableIndex}.students_per`,
        `applicable_sets.${applicableIndex}.no_of_instances`,
      ];

      sets.forEach((_: any, setIndex: number) => {
        fieldsToValidate.push(
          `applicable_sets.${applicableIndex}.sets.${setIndex}.set_name`,
          `applicable_sets.${applicableIndex}.sets.${setIndex}.has_bonus`,
          `applicable_sets.${applicableIndex}.sets.${setIndex}.min_students`,
          `applicable_sets.${applicableIndex}.sets.${setIndex}.max_students`,
        );
      });

      // ✅ FIRST: run schema validation
      const isTriggerValid = await trigger(fieldsToValidate as any);

      let isManualValid = true;

      // ✅ SECOND: run manual validation
      sets.forEach((_: any, setIndex: number) => {
        const instances =
          form.watch(
            `applicable_sets.${applicableIndex}.sets.${setIndex}.instances`,
          ) || [];

        instances.forEach((_: any, instanceIndex: number) => {
          const path = `applicable_sets.${applicableIndex}.sets.${setIndex}.instances.${instanceIndex}`;

          const commType = getValues(`${path}.commission_type`);
          const commAmount = getValues(`${path}.commission_amount`);

          const hasType = commType !== '';
          const hasAmount = commAmount !== '';

          // clear old errors
          clearErrors(`${path}.commission_type`);
          clearErrors(`${path}.commission_amount`);

          if (!hasType || commType === undefined) {
            setError(`${path}.commission_type`, {
              type: 'manual',
              message: 'Commission type is required',
            });
            isManualValid = false;
          }

          if (!hasAmount || commAmount === undefined) {
            setError(`${path}.commission_amount`, {
              type: 'manual',
              message: 'Commission amount is required',
            });
            isManualValid = false;
          }
        });
      });

      return isTriggerValid && isManualValid;
    },
    [trigger, getValues, setError, clearErrors],
  );

  const validateSingleSet = useCallback(
    async (applicableIndex: number, xsetIndex: number): Promise<boolean> => {
      const sets = getValues(`applicable_sets.${applicableIndex}.sets`);

      const fieldsToValidate: string[] = [];

      sets.forEach((_: any, setIndex: number) => {
        fieldsToValidate.push(
          `applicable_sets.${applicableIndex}.sets.${setIndex}.set_name`,
          `applicable_sets.${applicableIndex}.sets.${setIndex}.has_bonus`,
          `applicable_sets.${applicableIndex}.sets.${setIndex}.min_students`,
          `applicable_sets.${applicableIndex}.sets.${setIndex}.max_students`,
        );
      });

      // run schema validation
      const isTriggerValid = await trigger(fieldsToValidate as any);

      let isManualValid = true;

      // run manual validation
      sets.forEach((_: any, setIndex: number) => {
        const instances =
          form.watch(
            `applicable_sets.${applicableIndex}.sets.${setIndex}.instances`,
          ) || [];

        instances.forEach((_: any, instanceIndex: number) => {
          const path = `applicable_sets.${applicableIndex}.sets.${setIndex}.instances.${instanceIndex}`;

          const commType = getValues(`${path}.commission_type`);
          const commAmount = getValues(`${path}.commission_amount`);

          const hasType = commType !== '';
          const hasAmount = commAmount !== '';

          // clear old errors
          clearErrors(`${path}.commission_type`);
          clearErrors(`${path}.commission_amount`);

          if (!hasType || commType === undefined) {
            setError(`${path}.commission_type`, {
              type: 'manual',
              message: 'Commission type is required',
            });
            isManualValid = false;
          }

          if (!hasAmount || commAmount === undefined) {
            setError(`${path}.commission_amount`, {
              type: 'manual',
              message: 'Commission amount is required',
            });
            isManualValid = false;
          }
        });
      });

      return isTriggerValid && isManualValid;
    },
    [trigger, getValues, setError, clearErrors],
  );

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

  const handleOnOpen = useCallback(async () => {
    const fetchVisaProducts = async () => {
      const response = (await globalApiGet(
        API_ENDPOINTS.VCM.VISA_PRODUCTS,
      )) as ApiResponse<UnknownRecord[]>;

      return Array.isArray(response) ? response : [];
    };
    const fetchClientCountries = async () => {
      const response = (await globalApiGet(
        API_ENDPOINTS.VCM.CLIENT_COUNTRIES,
      )) as ApiResponse<UnknownRecord>;
      return Array.isArray(response) ? response : [];
    };
    try {
      const [visaProductsRes, clientCountriesRes] = await Promise.all([
        fetchVisaProducts(),
        fetchClientCountries(),
      ]);

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

  const handleProductChange = useCallback(
    async (productId: string) => {
      setValue('visa_service_country_id', '');
      setValue('associate_id', '');

      try {
        const vsCountries = await globalApiPost<ApiResponse<UnknownRecord[]>>(
          API_ENDPOINTS.VCM.VISA_SERVICE_COUNTRIES,
          {
            associate_type: contractType,
            product_id: String(productId),
          },
        );

        setVisaServiceCountries(Array.isArray(vsCountries) ? vsCountries : []);
      } catch (error) {
        console.error('Error loading visa service countries:', error);
        setVisaServiceCountries([]);
      }
    },
    [contractType, setValue],
  );

  const handleVisaCountryChange = useCallback(
    async (countryId: string) => {
      setValue('associate_id', '');

      const params: UnknownRecord = {
        association_type: contractType,
        country_id: String(countryId),
      };

      if (['2', '3'].includes(contractType as string)) {
        params.product_id = form.watch('product_id');
      }

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

        setAssociates(Array.isArray(associates) ? associates : []);
      } catch (error) {
        console.error('Error loading associates:', error);
        setAssociates([]);
      }
    },
    [contractType, setValue, form],
  );
  useEffect(() => {
    if (step === 2) {
      setValue('applicable_sets', [
        {
          applicable_campuses: [],
          applicable_study_levels: [],
          applicable_courses: [],
          no_of_instances: '',
          students_per: '',
          sets: [
            {
              set_name: '',
              min_students: '',
              max_students: '',
              has_bonus: '',
              bonus_type: '',
              bonus_amount: '',
              specific_contract: [],
              instances: [],
            },
          ],
        },
      ]);
    }
  }, [step, setValue]);
  const handleNext = useCallback(async () => {
    setIsNextLoading(true);

    // const applicableSets = getValues('applicable_sets') || [];

    // applicableSets.forEach((_: any, index: number) => {
    //   setValue(`applicable_sets.${index}.applicable_campuses`, []);
    //   setValue(`applicable_sets.${index}.applicable_study_levels`, []);
    //   setValue(`applicable_sets.${index}.applicable_courses`, []);
    // });

    const validateFields = [
      'product_id',
      'visa_service_country_id',
      'institute_id',
      'client_from_countries',
      'general_contract',
      'student_condition',
      'notes',
      'currency',
      'campus_condition',
      'study_level_condition',
      'course_condition',
    ];
    if (contractType !== '1') {
      validateFields.push('associate_id');
    }
    const isValid = await trigger(validateFields);
    if (contractType !== '1') {
      if (!form.watch('associate_id')) {
        setError('associate_id', {
          type: 'manual',
          message: 'Associate is required',
        });
        setIsNextLoading(false);
        return;
      }
    }

    if (!isValid) {
      setIsNextLoading(false);
      return;
    }

    clearErrors('applicable_sets');

    const instituteId = form.watch('institute_id');
    const countryId = form.watch('visa_service_country_id');
    const campusCondition = form.watch('campus_condition');
    const studyLevelCondition = form.watch('study_level_condition');
    const courseCondition = form.watch('course_condition');

    const duplicateCheckApiPayload = {
      association_type: associateType,
      product_id: form.watch('product_id'),
      visa_service_country_id: countryId,
      institute_id: instituteId,
      associate_id: null,
      client_from_countries: form.watch('client_from_countries'),
      student_condition: form.watch('student_condition'),
    };

    if (contractType !== '1')
      duplicateCheckApiPayload.associate_id = form.watch('associate_id');

    const isDuplicate = await globalApiPost<any>(
      API_ENDPOINTS.VCM.CHECK_DUPLICATE_RECORD,
      duplicateCheckApiPayload,
      false,
    );

    if (isDuplicate.success && isDuplicate.data === true) {
      showError('Duplicate record exists.', '');
      setIsNextLoading(false);
      return;
    }

    try {
      const tasks: Promise<void>[] = [];

      if (campusCondition === '2') {
        tasks.push(
          (async () => {
            const response = await globalApiPost<any>(
              API_ENDPOINTS.VCM.COLLEGE_CAMPUSES,
              {
                institute_id: instituteId,
                country_id: countryId,
              },
            );

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

      if (studyLevelCondition === '2') {
        tasks.push(
          (async () => {
            const response = await globalApiGet<any>(
              API_ENDPOINTS.VCM.STUDY_LEVELS,
            );

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

      if (courseCondition === '2') {
        tasks.push(
          (async () => {
            const response = await globalApiPost<any>(
              API_ENDPOINTS.VCM.FF_COURSES_BY_CAMPUS_STUDY_LEVELS,
              {
                institute_id: Number(instituteId),
                campuses: campuses.map((item) => item.id),
                study_levels: studyLevels.map((item) => item.id),
              },
            );

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

      await Promise.all(tasks);

      setStep(2);
    } catch (error) {
      console.error('Error loading campus/study level data:', error);
      setCampuses([]);
      setStudyLevels([]);
      setCourses([]);
    }
    setIsNextLoading(false);
  }, [trigger, clearErrors, form, setStep, contractType]);

  useEffect(() => {
    if (!isDialogOpen) {
      resetFormAndState();
    }
  }, [isDialogOpen]);

  const resetFormAndState = useCallback(() => {
    form.reset();
    setStep(1);
    setIsRange(false);
    setNoOfInstances({});
    setHasBonusByIndex({});
    setCampusCondition('');
    setStudyLevelCondition('');
    setCourseCondition('');
    fileManager.reset();

    setDropdownStates({
      product: false,
      visaServiceCountries: false,
      associate: false,
      studentCondition: false,
      range: false,
      currency: false,
      campus_condition: false,
      study_level_condition: false,
      course_condition: false,
      institute_id: false,
    });

    setCampuses([]);
    setStudyLevels([]);
    setCourses([]);
    setStudyLevelCoursesList({});
  }, [form, fileManager]);

  const onSubmit = useCallback(
    async (data: z.infer<typeof AddNewCommissionSchema>) => {
      try {
        let isTriggerValid: any = true;
        let isManualValid = true;

        const applicableSets = getValues(`applicable_sets`);

        for (
          let applicableIndex = 0;
          applicableIndex < applicableSets.length;
          applicableIndex++
        ) {
          const sets = getValues(`applicable_sets.${applicableIndex}.sets`);

          const fieldsToValidate: string[] = [];

          const seenNames = new Map<string, number>();
          let hasDuplicate = false;

          for (
            let applicableIndex = 0;
            applicableIndex < applicableSets.length;
            applicableIndex++
          ) {
            const sets = getValues(`applicable_sets.${applicableIndex}.sets`);

            const setNames: string[] = sets.map((_: any, setIndex: number) =>
              getValues(
                `applicable_sets.${applicableIndex}.sets.${setIndex}.set_name`,
              ),
            );

            for (let setIndex = 0; setIndex < sets.length; setIndex++) {
              const name: string = setNames[setIndex]?.trim() ?? '';

              if (name !== '') {
                if (seenNames.has(name)) {
                  hasDuplicate = true;
                  break;
                } else {
                  seenNames.set(name, setIndex);
                }
              }
            }

            if (hasDuplicate) break;
          }

          if (hasDuplicate) {
            toast({
              variant: 'warning',
              title: 'Set Name must be unique.',
              duration: 2000,
            });
            return;
          }

          sets.forEach((_: any, setIndex: number) => {
            fieldsToValidate.push(
              `applicable_sets.${applicableIndex}.sets.${setIndex}.set_name`,
              `applicable_sets.${applicableIndex}.sets.${setIndex}.has_bonus`,
              `applicable_sets.${applicableIndex}.sets.${setIndex}.min_students`,
              `applicable_sets.${applicableIndex}.sets.${setIndex}.max_students`,
            );
          });

          const triggerResult = await trigger(fieldsToValidate as any);
          if (!triggerResult) {
            isTriggerValid = false;
          }

          // Manual validation
          sets.forEach((_: any, setIndex: number) => {
            const instances =
              getValues(
                `applicable_sets.${applicableIndex}.sets.${setIndex}.instances`,
              ) || [];

            instances.forEach((_: any, instanceIndex: number) => {
              const path = `applicable_sets.${applicableIndex}.sets.${setIndex}.instances.${instanceIndex}`;

              const commType = getValues(`${path}.commission_type`);
              const commAmount = getValues(`${path}.commission_amount`);

              const hasType = commType !== '';
              const hasAmount = commAmount !== '';

              clearErrors(`${path}.commission_type`);
              clearErrors(`${path}.commission_amount`);

              if (!hasType || commType === undefined) {
                setError(`${path}.commission_type`, {
                  type: 'manual',
                  message: 'Commission type is required',
                });
                isManualValid = false;
              }

              if (!hasAmount || commAmount === undefined) {
                setError(`${path}.commission_amount`, {
                  type: 'manual',
                  message: 'Commission amount is required',
                });
                isManualValid = false;
              }
            });
          });
        }

        if (!isTriggerValid || !isManualValid) {
          toast({
            variant: 'warning',
            title: 'Please fill all required fields before adding a new set',
            duration: 2000,
          });
          return;
        }

        const formData = new FormData();
        fileManager.uploadedFiles.forEach((file) => {
          formData.append('general_contracts', file);
        });

        buildFormData({ ...data, general_contract: undefined }, formData);

        const res = await storeCommissionContract(formData);

        if ((res as any)?.success) {
          handlePaginatedRecords(1, {});
          form.reset();
          setStep(1);
          setIsDialogOpen(false);
          showSuccess(VCM_M.CONTRACT.SUBMIT);
        } else {
          showError((res as any)?.errors, VCM_M.CONTRACT.SUBMIT_ERROR);
        }
      } catch (error) {
        console.error('Submission error:', error);
        showError(error, VCM_M.CONTRACT.SUBMIT_ERROR);
      }
    },
    [fileManager.uploadedFiles, handlePaginatedRecords, form],
  );

  const handleStudentConditionChange = useCallback(
    (value: string) => {
      setIsRange(value === '2');
      // setValue('student_range', '');
    },
    [setValue],
  );

  const handleCloseDialog = useCallback(() => {
    // Reset will happen automatically via useEffect when isDialogOpen becomes false
    setIsDialogOpen(false);
  }, []);

  // Update DialogTrigger to reset form when opening
  const handleOpenDialog = useCallback(() => {
    // Reset form when opening to ensure clean state
    resetFormAndState();
    handleOnOpen();
    setIsDialogOpen(true);
    const el = document.querySelector('.table-menu-dropdown-widget');
    el?.classList.add('unactive');
  }, [resetFormAndState, handleOnOpen]);

  const [studyLevelCoursesList, setStudyLevelCoursesList] = useState<
    Record<number, { label: string; value: string }[]>
  >({});

  const handleCourseLevelsChange = async (index: number) => {
    const campuses: string[] = getValues(
      `applicable_sets.${index}.applicable_campuses`,
    );
    const studyLevels: string[] = getValues(
      `applicable_sets.${index}.applicable_study_levels`,
    );

    if (!campuses?.length || !studyLevels?.length) {
      setStudyLevelCoursesList((prev) => ({ ...prev, [index]: [] }));
      return;
    }

    try {
      const courses: any = await globalApiPost(
        API_ENDPOINTS.VCM.FF_COURSES_BY_CAMPUS_STUDY_LEVELS,
        {
          institute_id: Number(getValues('associate_id')),
          campuses,
          study_levels: studyLevels,
        },
      );

      setStudyLevelCoursesList((prev) => ({
        ...prev,
        [index]: courses
          ? (transformMultipleSelectOptions(courses) as {
              label: string;
              value: string;
            }[])
          : [],
      }));
    } catch (err) {
      console.log('Failed to fetch courses:', err);
      setStudyLevelCoursesList((prev) => ({ ...prev, [index]: [] }));
    }
  };

  // Add new set to an applicable set
  const handleAddSet = useCallback(
    async (applicableIndex: number, setIndex: number) => {
      const isValid = await validateSingleSet(applicableIndex, setIndex);
      if (!isValid) {
        toast({
          variant: 'warning',
          title: 'Please fill all required fields before adding a new set',
          duration: 2000,
        });
        return;
      }
      const currentSets = getValues(`applicable_sets.${applicableIndex}.sets`);
      const count =
        Number(
          getValues(`applicable_sets.${applicableIndex}.no_of_instances`),
        ) || 0;
      const instances = Array.from({ length: count }, (_, i) => ({
        id: crypto.randomUUID(),
        instance: String(i + 1),
        commission_type: '',
        commission_amount: '',
      }));
      const updatedSets = [
        ...currentSets,
        {
          set_name: '',
          min_students: '',
          max_students: '',
          has_bonus: '',
          bonus_type: '',
          bonus_amount: '',
          specific_contract: [],
          instances: instances,
        },
      ];

      setValue(`applicable_sets.${applicableIndex}.sets`, updatedSets, {
        shouldDirty: true,
        shouldTouch: true,
        shouldValidate: false,
      });

      const newSetIndex = updatedSets.length - 1;

      clearErrors(`applicable_sets.${applicableIndex}.sets.${newSetIndex}`);
    },
    [validateSingleSet, getValues, setValue, toast],
  );

  // Remove set from an applicable set
  const handleRemoveSet = useCallback(
    (applicableIndex: number, setIndex: number) => {
      const currentSets = getValues(`applicable_sets.${applicableIndex}.sets`);
      const updatedSets = currentSets.filter(
        (_: any, i: number) => i !== setIndex,
      );
      setValue(`applicable_sets.${applicableIndex}.sets`, updatedSets);

      // Clear errors for removed set
      clearErrors(`applicable_sets.${applicableIndex}.sets.${setIndex}`);
    },
    [getValues, setValue, clearErrors],
  );

  const fetchInstitutes = useCallback(async (country_id: string) => {
    const response = await globalApiPost(API_ENDPOINTS.VCM.INSTITUTE_LIST, {
      country_id,
    });

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

  // Add new applicable set
  const handleAddApplicableSet = useCallback(async () => {
    const lastIndex = applicableSets.length - 1;
    const isValid = await validateAllSetsInApplicableSet(lastIndex);

    if (isValid) {
      appendApplicableSet({
        applicable_campuses: [],
        applicable_study_levels: [],
        applicable_courses: [],
        no_of_instances: '',
        students_per: '',
        sets: [
          {
            set_name: '',
            min_students: '',
            max_students: '',
            has_bonus: '',
            bonus_type: '',
            bonus_amount: '',
            specific_contract: [],
            instances: [],
          },
        ],
      });
    } else {
      toast({
        variant: 'warning',
        title:
          'Please fill all required fields before adding a new applicable set',
        duration: 2000,
      });
    }
  }, [
    applicableSets.length,
    validateAllSetsInApplicableSet,
    appendApplicableSet,
    toast,
  ]);

  return (
    <Dialog open={isDialogOpen}>
      <DialogTrigger onClick={handleOpenDialog} 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 Contract - {contractTypeLabel}
        </DialogTitle>
        <DialogDescription>{''}</DialogDescription>
        <DialogClose asChild>
          <button
            onClick={handleCloseDialog}
            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">
                {step === 1 && (
                  <>
                    <input
                      type="hidden"
                      name="association_type"
                      id="association_type"
                      value={String(contractType)}
                    />

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

                    <FormField
                      control={control}
                      name="visa_service_country_id"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Visa Service Country"
                          placeholder="Choose Visa Service Country"
                          options={visaServiceCountries.map((item: any) => ({
                            id: item.country_id,
                            name: item.name,
                          }))}
                          isOpen={dropdownStates.visaServiceCountries}
                          onOpenChange={() =>
                            toggleDropdown('visaServiceCountries')
                          }
                          onSelect={(value) => {
                            field.onChange(String(value));
                            clearErrors('visa_service_country_id');
                            setDropdownStates((prev) => ({
                              ...prev,
                              visaServiceCountries: false,
                            }));
                            setValue(`institute_id`, '');
                            handleVisaCountryChange(String(value));
                            fetchInstitutes(String(value));
                          }}
                          required
                        />
                      )}
                    />

                    {associateType !== '1' && (
                      <FormField
                        control={control}
                        name="associate_id"
                        render={({ field }) => (
                          <SearchableSelect
                            field={field}
                            label="Associate"
                            placeholder="Choose Associate"
                            options={associates.map((item: any) => ({
                              id: String(item.id),
                              name: item.name,
                            }))}
                            isOpen={dropdownStates.associate}
                            onOpenChange={() => toggleDropdown('associate')}
                            onSelect={(value) => {
                              field.onChange(String(value));
                              clearErrors('associate_id');
                              setDropdownStates((prev) => ({
                                ...prev,
                                associate: false,
                              }));
                              setValue(`institute_id`, '');
                            }}
                            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));
                            clearErrors('institute_id');
                            setDropdownStates((prev) => ({
                              ...prev,
                              institute_id: false,
                            }));
                          }}
                          required
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="client_from_countries"
                      render={({ field }) => (
                        <FormItem className="w-full md:w-1/2 lg:w-1/4 p-2">
                          <FormLabel className="font-bold">
                            <span className="text-red-600 pl-1">*</span>
                            Client Country
                          </FormLabel>
                          <MultiSelect
                            options={clientCountries || []}
                            onValueChange={(value) => {
                              field.onChange(value);
                              clearErrors('client_from_countries');
                            }}
                            value={field.value ?? []}
                            placeholder="Choose Client Country"
                            maxCount={1}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={control}
                      name="student_condition"
                      render={({ field }) => (
                        <SearchableSelect
                          field={field}
                          label="Student Condition"
                          placeholder="Choose Student Condition"
                          options={STUDENT_CONDITION_LIST.map((item) => ({
                            id: String(item.id),
                            name: item.name,
                          }))}
                          isOpen={dropdownStates.studentCondition}
                          onOpenChange={() =>
                            toggleDropdown('studentCondition')
                          }
                          onSelect={(value) => {
                            field.onChange(String(value));
                            clearErrors('student_condition');
                            setDropdownStates((prev) => ({
                              ...prev,
                              studentCondition: false,
                            }));
                            handleStudentConditionChange(String(value));
                          }}
                          required
                        />
                      )}
                    />

                    <Controller
                      control={control}
                      name="general_contract"
                      render={({ field }) => (
                        <FileUploadField
                          field={field as any}
                          label={`General Contract (Allowed: ${ATTACHMENT_VALIDATION_CONTRACT.label})`}
                          acceptFileFormat={ATTACHMENT_VALIDATION_CONTRACT.allowedTypes
                            .map((t) => `.${t}`)
                            .join(',')}
                          maxFiles={ATTACHMENT_VALIDATION_CONTRACT.maxFiles}
                          maxFileSize={
                            ATTACHMENT_VALIDATION_CONTRACT.maxFileSize
                          }
                          acceptFileFormatLabel={
                            ATTACHMENT_VALIDATION_CONTRACT.label
                          }
                          files={fileManager.uploadedFiles}
                          onFilesChange={fileManager.setUploadedFiles}
                          dropdownOpen={fileManager.dropdownOpen}
                          onToggleDropdown={() =>
                            fileManager.setDropdownOpen(
                              !fileManager.dropdownOpen,
                            )
                          }
                          onRemoveFile={(index) =>
                            fileManager.handleRemoveFile(index, fileInputRef)
                          }
                          // fileInputRef={fileInputRef}
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="currency"
                      render={({ field }) => {
                        const filteredCurrencies = CURRENCY_LIST.filter(
                          (currency) => {
                            if (contractType === '3') {
                              return ['INR'].includes(currency.id);
                            }
                            return true;
                          },
                        );

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

                    <ConditionFields
                      control={control}
                      clearErrors={clearErrors}
                      dropdownStates={dropdownStates}
                      toggleDropdown={toggleDropdown}
                      setDropdownStates={setDropdownStates}
                      onCampusConditionChange={setCampusCondition}
                      onStudyLevelConditionChange={setStudyLevelCondition}
                      onCourseConditionChange={setCourseCondition}
                      campusCondition={campusCondition}
                      studyLevelCondition={studyLevelCondition}
                      courseCondition={courseCondition}
                      conditionOptions={ALL_SPECIFIC}
                    />

                    <FormField
                      control={control}
                      name="notes"
                      render={({ field }) => (
                        <FormItem className="w-full p-2">
                          <FormLabel htmlFor="notes" className="font-bold">
                            <span className="text-red-600 pl-1">*</span>
                            Important Conditions / Notes
                          </FormLabel>
                          <Textarea
                            id="notes"
                            placeholder="Type your message here."
                            className="py-1 mt-2 rounded-lg p-2 pl-2 pr-6 border-gray-600 h-32"
                            value={field.value}
                            onChange={(e) => {
                              field.onChange(e);
                              clearErrors('notes');
                            }}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </>
                )}

                {step === 2 && (
                  <>
                    {applicableSets.map((applicableSet, applicableIndex) => (
                      <div
                        key={applicableSet.id}
                        className="commission-set-addon border border-solid border-gray-400 rounded-sm p-4 m-2 w-full"
                      >
                        {(campusCondition === '2' ||
                          studyLevelCondition === '2' ||
                          courseCondition === '2') && (
                          <div className="w-full common-type flex justify-between ml-2 commission-set-header mb-4">
                            <div className="heading">
                              Applicable On Set - {applicableIndex + 1}
                            </div>
                            <div className="commission-action flex gap-2 mr-4">
                              {applicableIndex > 0 && (
                                <Button
                                  type="button"
                                  className="active-btn hide-widget"
                                  onClick={() =>
                                    removeApplicableSet(applicableIndex)
                                  }
                                >
                                  -
                                </Button>
                              )}
                              {(campusCondition === '2' ||
                                studyLevelCondition === '2' ||
                                courseCondition === '2') &&
                                applicableIndex ===
                                  applicableSets.length - 1 && (
                                  <Button
                                    type="button"
                                    className="active-btn show-widget"
                                    onClick={handleAddApplicableSet}
                                  >
                                    +
                                  </Button>
                                )}
                            </div>
                          </div>
                        )}

                        <div className="w-full">
                          <div className="flex flex-wrap">
                            <FormField
                              control={control}
                              name={`applicable_sets.${applicableIndex}.students_per`}
                              render={({ field }) => (
                                <FormItem className="w-full md:w-1/2 lg:w-1/4 p-2">
                                  <FormLabel className="font-bold">
                                    <span className="text-red-600 pl-1">*</span>
                                    Students Per
                                  </FormLabel>
                                  <Select
                                    value={field.value}
                                    onValueChange={(value) => {
                                      field.onChange(value);
                                      clearErrors(
                                        `applicable_sets.${applicableIndex}.students_per`,
                                      );
                                    }}
                                  >
                                    <SelectTrigger>
                                      <SelectValue placeholder="Select Students Per" />
                                    </SelectTrigger>
                                    <SelectContent className="z-[9999]">
                                      {VC_STUDENTS_DURATION.map((item) => (
                                        <SelectItem
                                          key={String(item.id)}
                                          value={String(item.id)}
                                        >
                                          {item.name}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />

                            <FormField
                              control={control}
                              name={`applicable_sets.${applicableIndex}.no_of_instances`}
                              render={({ field }) => (
                                <FormItem className="w-full md:w-1/2 lg:w-1/4 p-2">
                                  <FormLabel className="font-bold">
                                    <span className="text-red-600 pl-1">*</span>
                                    No of Commission Instance
                                  </FormLabel>
                                  <Select
                                    value={field.value}
                                    onValueChange={(value) => {
                                      field.onChange(value);

                                      const count = Math.max(
                                        0,
                                        Number(value) || 0,
                                      );
                                      const key = `${applicableIndex}`;

                                      clearErrors(
                                        `applicable_sets.${applicableIndex}.no_of_instances`,
                                      );

                                      setNoOfInstances((prev) => ({
                                        ...prev,
                                        [key]: count,
                                      }));

                                      const sets =
                                        getValues(
                                          `applicable_sets.${applicableIndex}.sets`,
                                        ) || [];

                                      sets.forEach(
                                        (_: any, setIndex: number) => {
                                          const path = `applicable_sets.${applicableIndex}.sets.${setIndex}.instances`;

                                          const newInstances = Array.from(
                                            { length: count },
                                            (_, i) => ({
                                              id: crypto.randomUUID(),
                                              instance: String(i + 1),
                                              commission_type: '',
                                              commission_amount: '',
                                            }),
                                          );

                                          setValue(path, newInstances, {
                                            shouldDirty: true,
                                            shouldValidate: true,
                                          });

                                          clearErrors(path);
                                        },
                                      );
                                    }}
                                  >
                                    <SelectTrigger>
                                      <SelectValue placeholder="Select Commission Instance" />
                                    </SelectTrigger>
                                    <SelectContent className="z-[9999]">
                                      {COMMISSION_INSTANCE_OPTIONS.map(
                                        (item) => (
                                          <SelectItem
                                            key={item.value}
                                            value={item.value}
                                          >
                                            {item.label}
                                          </SelectItem>
                                        ),
                                      )}
                                    </SelectContent>
                                  </Select>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          </div>
                        </div>
                        {/* Applicable On Section */}
                        {(campusCondition === '2' ||
                          studyLevelCondition === '2' ||
                          courseCondition === '2') && (
                          <ApplicableOnSection
                            control={control}
                            clearErrors={clearErrors}
                            index={applicableIndex}
                            campusCondition={campusCondition}
                            studyLevelCondition={studyLevelCondition}
                            courseCondition={courseCondition}
                            campuses={campuses as any}
                            studyLevels={studyLevels as any}
                            studyLevelCoursesList={courses}
                            onCourseLevelsChange={handleCourseLevelsChange}
                          />
                        )}

                        <div className="commission-instance-widget mt-4 mb-4">
                          <div className="heading ml-2">Sets</div>
                        </div>

                        {/* Dynamic Sets */}
                        {getValues(
                          `applicable_sets.${applicableIndex}.sets`,
                        )?.map((set: any, setIndex: number) => (
                          <div
                            key={setIndex}
                            className="border border-solid border-gray-200 rounded-sm p-4 m-2 w-full"
                          >
                            <div className="w-full common-type flex justify-between ml-2 commission-set-header mb-4">
                              <div className="heading">
                                Commission Set - {setIndex + 1}
                              </div>
                              <div className="commission-action flex gap-2 mr-4">
                                {setIndex > 0 && (
                                  <Button
                                    type="button"
                                    className="active-btn hide-widget"
                                    onClick={() =>
                                      handleRemoveSet(applicableIndex, setIndex)
                                    }
                                  >
                                    -
                                  </Button>
                                )}
                                {isRange &&
                                  setIndex ===
                                    getValues(
                                      `applicable_sets.${applicableIndex}.sets`,
                                    ).length -
                                      1 && (
                                    <Button
                                      type="button"
                                      className="active-btn show-widget"
                                      onClick={() =>
                                        handleAddSet(applicableIndex, setIndex)
                                      }
                                    >
                                      +
                                    </Button>
                                  )}
                              </div>
                            </div>

                            <div className="w-full">
                              <div className="flex flex-wrap">
                                <FormField
                                  control={control}
                                  name={`applicable_sets.${applicableIndex}.sets.${setIndex}.set_name`}
                                  render={({ field }) => (
                                    <FormItem className="w-full md:w-1/2 lg:w-1/4 p-2 rounded-full">
                                      <FormLabel className="no-error-styles font-bold">
                                        <span className="text-red-600 pl-1">
                                          *
                                        </span>
                                        Set Name
                                      </FormLabel>
                                      <FormControl>
                                        <Input
                                          autoComplete="off"
                                          className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                                          placeholder="Enter Value"
                                          {...field}
                                          onChange={(e) => {
                                            field.onChange(e.target.value);
                                            clearErrors(
                                              `applicable_sets.${applicableIndex}.sets.${setIndex}.set_name`,
                                            );
                                          }}
                                        />
                                      </FormControl>
                                      <FormMessage />
                                    </FormItem>
                                  )}
                                />

                                {isRange && (
                                  <StudentRangeFields
                                    control={control}
                                    clearErrors={clearErrors}
                                    applicableIndex={applicableIndex}
                                    setIndex={setIndex}
                                    isRange={isRange}
                                  />
                                )}

                                <BonusFields
                                  control={control}
                                  clearErrors={clearErrors}
                                  applicableIndex={applicableIndex}
                                  setIndex={setIndex}
                                  hasBonus={
                                    hasBonusByIndex[
                                      `${applicableIndex}-${setIndex}`
                                    ]
                                  }
                                  onHasBonusChange={handleHasBonusChange}
                                  hasBonusOptions={VC_HAS_BONUS}
                                  bonusTypeOptions={VC_BONUS_TYPE}
                                  getValues={getValues}
                                  setValue={setValue}
                                />

                                <Controller
                                  control={control}
                                  name={`applicable_sets.${applicableIndex}.sets.${setIndex}.specific_contract`}
                                  render={({ field }) => {
                                    const specificFiles =
                                      fileManager.filesByIndex[
                                        `${applicableIndex}-${setIndex}` as any
                                      ] || [];
                                    const dropdownOpen =
                                      fileManager.dropdownsByIndex[
                                        `${applicableIndex}-${setIndex}` as any
                                      ] || false;

                                    return (
                                      <FileUploadField
                                        field={field as any}
                                        label={`Specific Contract (Allowed: ${ATTACHMENT_VALIDATION_CONTRACT.label})`}
                                        acceptFileFormat={ATTACHMENT_VALIDATION_CONTRACT.allowedTypes
                                          .map((t) => `.${t}`)
                                          .join(',')}
                                        maxFiles={
                                          ATTACHMENT_VALIDATION_CONTRACT.maxFiles
                                        }
                                        maxFileSize={
                                          ATTACHMENT_VALIDATION_CONTRACT.maxFileSize
                                        }
                                        acceptFileFormatLabel={
                                          ATTACHMENT_VALIDATION_CONTRACT.label
                                        }
                                        files={specificFiles}
                                        onFilesChange={(newFiles) => {
                                          fileManager.setFilesByIndex(
                                            (prev) => ({
                                              ...prev,
                                              [`${applicableIndex}-${setIndex}`]:
                                                newFiles,
                                            }),
                                          );
                                          field.onChange(newFiles);
                                        }}
                                        dropdownOpen={dropdownOpen}
                                        onToggleDropdown={() =>
                                          fileManager.toggleDropdown(
                                            `${applicableIndex}-${setIndex}` as any,
                                          )
                                        }
                                        onRemoveFile={(fileIndex) =>
                                          fileManager.handleRemoveSpecificFile(
                                            `${applicableIndex}-${setIndex}` as any,
                                            fileIndex,
                                            field,
                                          )
                                        }
                                        // fileInputRef={fileInputRef}
                                      />
                                    );
                                  }}
                                />
                              </div>

                              {/* Commission Instances */}
                              {form.watch(
                                `applicable_sets.${applicableIndex}.sets.${setIndex}.instances`,
                              ).length > 0 && (
                                <CommissionInstancesSection
                                  control={control}
                                  clearErrors={clearErrors}
                                  applicableIndex={applicableIndex}
                                  setIndex={setIndex}
                                  noOfInstances={
                                    form.watch(
                                      `applicable_sets.${applicableIndex}.sets.${setIndex}.instances`,
                                    ).length || 0
                                  }
                                  commissionTypeOptions={VC_COMMISSION_TYPE}
                                  getValues={getValues}
                                  setValue={setValue}
                                  form={form}
                                />
                              )}
                            </div>
                          </div>
                        ))}
                      </div>
                    ))}
                  </>
                )}
              </Text>
            </Text>

            {/* Footer Buttons */}
            <FooterButtons
              step={step}
              setStep={setStep}
              handleNext={handleNext}
              isSubmitting={isSubmitting}
              isNextLoading={isNextLoading}
            />
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
};

export default AddCommissionContract;
