'use client';

import React, { useState, useCallback, useMemo, useEffect } from 'react';
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogTitle,
  DialogDescription,
  DialogClose,
} from '@/components/ui/dialog';
import CommonImage from '@/components/common/CommonImage';
import { Text } from '@/components/ui/text';
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
import { useForm, useFieldArray } from 'react-hook-form';
import { Textarea } from '@/components/ui/textarea';
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Button } from '@/components/ui/button';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  ALL_SPECIFIC,
  API_ENDPOINTS,
  CURRENCY_LIST,
  VC_ASSOCIATE_TYPES,
  VC_BONUS_TYPE,
  VC_COMMISSION_TYPE,
  VC_HAS_BONUS,
} from '@/constants';
import { useToast } from '@/hooks/use-toast';
import { transformMultipleSelectOptions } from '@/utils/transformers';
import {
  UnknownRecord,
  ApiResponse,
  fnEmpty,
  HandlePaginatedRecords,
  fnAny,
  BucketProp,
} from '@/types';
import { globalApiGet, globalApiPost } from '@/services/global/globalApiCalls';
import {
  applicableSetsEmptyState,
  buildFormData,
  mapCommissionContractSets,
  prepareEditFormDefaultValues,
} from './constants';
import ConditionFields from '../form-components/edit-commission/ConditionFields';
import { NumericDisplayField } from '../form-components/edit-commission/NumericDisplayField';
import { VisaServiceCountryField } from '../form-components/edit-commission/VisaServiceCountryField';
import { ProductField } from '../form-components/edit-commission/ProductField';
import { ClientCountryField } from '../form-components/edit-commission/ClientCountryField';
import { useCommissionOperations } from '@/hooks/useCommissionOperations';
import ApplicableSetCard from '../form-components/edit-commission/ApplicableSetCard';
import { SearchableSelect } from './SearchableSelect';
import { FooterButtons } from './FooterButtons';
import { VCM_M } from '@/constants/typo/submit-alerts';
import { useAppToast } from '@/hooks/useAppToast';

type EditCommissionContractProps = {
  triggerIcon?: React.ReactNode;
  bucket: BucketProp['bucket'];
  handleCloseTooltip: fnEmpty;
  handlePaginatedRecords: HandlePaginatedRecords;
  record: UnknownRecord;
  setActiveRow: fnAny;
};

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

  // State management
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [step, setStep] = useState(1);
  const [nextClicked, setNextClicked] = useState(false);

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

  // Data states
  const [campuses, setCampuses] = useState<UnknownRecord[]>([]);
  const [studyLevels, setStudyLevels] = useState<UnknownRecord[]>([]);
  const [clientCountries, setClientCountries] = useState<any>([]);
  const [courses, setCourses] = useState<any>([]);

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

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

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

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

  const [campusCondition, setCampusCondition] = useState<string>('1');
  const [studyLevelCondition, setStudyLevelCondition] = useState<string>('1');
  const [courseCondition, setCourseCondition] = useState<string>('1');
  const [studentCondition, setStudentCondition] = useState<string>('1');
  const [currency, setCurrency] = useState<string>('');
  const [isNextLoading, setIsNextLoading] = useState(false);

  // Enhanced Zod Schema with dynamic sets validation
  const EditNewCommissionSchema = bucket?.crud?.edit.schema.validator;

  const form = useForm<z.infer<typeof EditNewCommissionSchema>>({
    resolver: zodResolver(EditNewCommissionSchema),
    defaultValues: prepareEditFormDefaultValues(record),
  });

  const {
    control,
    formState: { isSubmitting },
    setValue,
    clearErrors,
    setError,
    trigger,
    getValues,
    reset, // Add reset to destructuring
  } = form;

  const {
    fields: applicableSets,
    append: appendApplicableSet,
    remove: removeApplicableSet,
    append,
    replace,
  } = 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 { handleAddSet, handleRemoveSet, handleAddApplicableSet } =
    useCommissionOperations(
      getValues,
      trigger,
      setValue,
      clearErrors,
      setError,
    );

  // Function to reset all states to initial values
  const resetAllStates = useCallback(() => {
    // Reset form to original record values
    reset(prepareEditFormDefaultValues(record));

    setStep(1);
    setNextClicked(false);

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

    // Reset data states
    setCampuses([]);
    setStudyLevels([]);
    setClientCountries([]);
    setCourses([]);

    // Reset UI states
    setIsRange(
      record.student_condition === '2' || record.student_condition === 2,
    );
    setNoOfInstances({});
    setHasBonusByIndex({});
    setCampusCondition(String(record.campus_condition));
    setStudyLevelCondition(String(record.study_level_condition));
    setCourseCondition(String(record.course_condition));
    setStudentCondition(String(record.student_condition));
    setCurrency(String(record.currency));
    setIsNextLoading(false);
  }, [record, reset]);

  const handleDialogClose = useCallback(() => {
    resetAllStates();
    setIsDialogOpen(false);
  }, [resetAllStates]);

  const handleDialogOpen = useCallback(async () => {
    resetAllStates(); // Reset states before opening
    await handleOnOpen();
    setIsDialogOpen(true);
    await loadDefaultValues();
  }, [resetAllStates]);

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

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

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

  const handleNext = useCallback(async () => {
    setNextClicked(true);
    setIsNextLoading(true);
    const cols = [
      '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') {
      cols.push('associate_id');
    }

    const isValid = await trigger(cols);

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

    clearErrors('applicable_sets');

    const instituteId = form.watch('institute_id');
    const countryId = form.watch('visa_service_country_id');

    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'),
      id: String(record.id),
    };

    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 (form.watch('campus_condition') === '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 (form.watch('study_level_condition') === '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 (form.watch('course_condition') === '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);
          })(),
        );
      }

      // ✅ Wait for both to complete before moving to step 2
      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,
    associateType,
    record.id,
    contractType,
    showError,
    campuses,
    studyLevels,
  ]);

  const onSubmit = useCallback(
    async (data: z.infer<typeof EditNewCommissionSchema>) => {
      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;
          }

          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();

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

        const res = await globalApiPost(
          API_ENDPOINTS.VCM.EDIT_COMMISSION_CONTRACTS,
          formData,
          false,
        );
        if ((res as any)?.success) {
          handlePaginatedRecords(1, {});
          handleDialogClose(); // Use handleDialogClose instead of manual reset
          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);
      }
    },
    [
      handlePaginatedRecords,
      handleDialogClose,
      record.id,
      showSuccess,
      showError,
    ],
  );

  const handleStudentConditionChange = useCallback(
    (value: string) => {
      setIsRange(value === '2');
      setStudentCondition(value);
    },
    [], // Remove setValue dependency as it's not used
  );

  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]: [] }));
    }
  };

  const [commissionContractInfo, setCommissionContractInfo] =
    useState<UnknownRecord>({});

  async function loadDefaultValues() {
    setStep(1);
    setNextClicked(false);
    const info = await globalApiGet<any>(
      `${API_ENDPOINTS.VCM.COMMISSION_CONTRACT_INFO}/${record.id}`,
    );

    if (
      info &&
      info?.vcm_commission_contract_applicable_sets &&
      Array.isArray(info.vcm_commission_contract_applicable_sets)
    ) {
      setCommissionContractInfo(info);

      // Set noOfInstances from the loaded data
      const initialNoOfInstances: Record<string, number> = {};
      const initialHasBonus: Record<string, boolean> = {};

      info.vcm_commission_contract_applicable_sets.forEach(
        (applicableSet: UnknownRecord, applicableIndex: number) => {
          const key = `${applicableIndex}`;
          initialNoOfInstances[key] = applicableSet.no_of_instances
            ? parseInt(String(applicableSet.no_of_instances), 10)
            : 0;

          // Set hasBonusByIndex
          if (Array.isArray(applicableSet.vcm_commission_contract_sets)) {
            applicableSet.vcm_commission_contract_sets.forEach(
              (set: UnknownRecord, setIndex: number) => {
                const bonusKey = `${applicableIndex}-${setIndex}`;
                initialHasBonus[bonusKey] = set.has_bonus === '1';
              },
            );
          }
        },
      );

      setNoOfInstances(initialNoOfInstances);
      setHasBonusByIndex(initialHasBonus);

      const mappedSets = mapCommissionContractSets(info);

      replace(mappedSets);
    } else if (applicableSets.length === 0) {
      append(applicableSetsEmptyState);
    }
  }

  useEffect(() => {
    if (record.student_condition === '2' || record.student_condition === 2) {
      setIsRange(true);
    }
    setCampusCondition(String(record.campus_condition));
    setStudyLevelCondition(String(record.study_level_condition));
    setCourseCondition(String(record.course_condition));
    setStudentCondition(String(record.student_condition));
    setCurrency(String(record.currency));
  }, [record]);

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

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

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit, (errors) => {
              console.log('Zod validation errors:', errors);
            })}
            className="space-y-6"
            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
                      name={`product_id`}
                      control={control}
                      render={({ field }) => (
                        <ProductField
                          field={field}
                          record={record}
                          bucket={bucket}
                        />
                      )}
                    />
                    <FormField
                      name={`visa_service_country_id`}
                      control={control}
                      render={({ field }) => (
                        <VisaServiceCountryField
                          field={field}
                          record={record}
                          bucket={bucket}
                        />
                      )}
                    />
                    {contractType !== '1' && (
                      <FormField
                        name={`associate_id`}
                        control={control}
                        render={({ field }) => (
                          <NumericDisplayField
                            field={field}
                            record={record}
                            bucket={bucket}
                            columnKey="associate_id"
                            label="Associate"
                          />
                        )}
                      />
                    )}
                    <FormField
                      name={`institute_id`}
                      control={control}
                      render={({ field }) => (
                        <NumericDisplayField
                          field={field}
                          record={record}
                          bucket={bucket}
                          columnKey="institute_id"
                          label="Institute"
                        />
                      )}
                    />

                    <FormField
                      control={control}
                      name="client_from_countries"
                      render={({ field }) => (
                        <ClientCountryField
                          field={field}
                          clientCountries={clientCountries}
                          clearErrors={clearErrors}
                          prev={record.client_from_countries}
                        />
                      )}
                    />
                    <FormField
                      name={`student_condition`}
                      control={control}
                      render={({ field }) => (
                        <NumericDisplayField
                          field={field}
                          record={record}
                          bucket={bucket}
                          columnKey="student_condition"
                          label="Student Condition"
                        />
                      )}
                    />

                    <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}
                      conditionOptions={ALL_SPECIFIC}
                      campusCondition={campusCondition}
                      studyLevelCondition={studyLevelCondition}
                      courseCondition={courseCondition}
                      record={record}
                    />

                    <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"
                            defaultValue={record.notes ?? field.value}
                            onChange={(e) => {
                              field.onChange(e);
                              clearErrors('notes');
                            }}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </>
                )}

                {step === 2 && (
                  <>
                    {applicableSets.map((applicableSet, applicableIndex) => (
                      <ApplicableSetCard
                        key={applicableSet.id}
                        control={control}
                        clearErrors={clearErrors}
                        getValues={getValues}
                        setValue={setValue}
                        applicableIndex={applicableIndex}
                        applicableSet={applicableSet}
                        applicableSets={applicableSets}
                        campusCondition={campusCondition}
                        studyLevelCondition={studyLevelCondition}
                        courseCondition={courseCondition}
                        isRange={isRange}
                        hasBonusByIndex={hasBonusByIndex}
                        noOfInstances={noOfInstances}
                        setNoOfInstances={setNoOfInstances}
                        campuses={campuses}
                        studyLevels={studyLevels}
                        studyLevelCoursesList={courses}
                        commissionContractInfo={commissionContractInfo}
                        removeApplicableSet={removeApplicableSet}
                        handleAddApplicableSet={handleAddApplicableSet}
                        handleCourseLevelsChange={handleCourseLevelsChange}
                        handleHasBonusChange={handleHasBonusChange}
                        handleRemoveSet={handleRemoveSet}
                        handleAddSet={handleAddSet}
                        appendApplicableSet={appendApplicableSet}
                        hasBonusOptions={VC_HAS_BONUS}
                        bonusTypeOptions={VC_BONUS_TYPE}
                        commissionTypeOptions={VC_COMMISSION_TYPE}
                        form={form}
                      />
                    ))}
                  </>
                )}
              </Text>
            </Text>

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

export default EditCommissionContract;
