import React from 'react';
import {
  Control,
  UseFormClearErrors,
  UseFormGetValues,
  UseFormSetValue,
  Controller,
  useFieldArray,
} from 'react-hook-form';
import { Button } from '@/components/ui/button';
import StudentsPerField from './StudentsPerField';
import NoOfInstancesField from './NoOfInstancesField';
import ApplicableOnSection from './ApplicableOnSection';
import CommissionSetCard from './CommissionSetCard';
import { UnknownRecord } from '@/types';

interface ApplicableSetCardProps {
  control: Control<any>;
  clearErrors: UseFormClearErrors<any>;
  getValues: UseFormGetValues<any>;
  setValue: UseFormSetValue<any>;
  applicableIndex: number;
  applicableSet: any;
  applicableSets: any[];
  campusCondition: string;
  studyLevelCondition: string;
  courseCondition: string;
  isRange: boolean;
  hasBonusByIndex: Record<string, boolean>;
  noOfInstances: Record<string, number>;
  setNoOfInstances: React.Dispatch<
    React.SetStateAction<Record<string, number>>
  >; // Add this prop
  campuses: any[];
  studyLevels: any[];
  studyLevelCoursesList: any[];
  commissionContractInfo?: UnknownRecord;
  removeApplicableSet: (index: number) => void;
  handleAddApplicableSet: (
    applicableSets: any[],
    appendApplicableSet: any,
  ) => void;
  handleCourseLevelsChange: (index: number) => void;
  handleHasBonusChange: (
    applicableIndex: number,
    setIndex: number,
    value: string,
  ) => void;
  handleRemoveSet: (applicableIndex: number, setIndex: number) => void;
  handleAddSet: (applicableIndex: number, setIndex: number) => void;
  appendApplicableSet: any;
  hasBonusOptions: Array<{ id: number | string; name: string }>;
  bonusTypeOptions: Array<{ id: number | string; name: string }>;
  commissionTypeOptions: Array<{ id: number | string; name: string }>;
  form: any;
}

const ApplicableSetCard: React.FC<ApplicableSetCardProps> = ({
  control,
  clearErrors,
  getValues,
  setValue,
  applicableIndex,
  applicableSet,
  applicableSets,
  campusCondition,
  studyLevelCondition,
  courseCondition,
  isRange,
  hasBonusByIndex,
  noOfInstances,
  setNoOfInstances, // Add this to destructuring
  campuses,
  studyLevels,
  studyLevelCoursesList,
  commissionContractInfo,
  removeApplicableSet,
  handleAddApplicableSet,
  handleCourseLevelsChange,
  handleHasBonusChange,
  handleRemoveSet,
  handleAddSet,
  appendApplicableSet,
  hasBonusOptions,
  bonusTypeOptions,
  commissionTypeOptions,
  form,
}) => {
  const showConditionalSections =
    String(campusCondition) === '2' ||
    String(studyLevelCondition) === '2' ||
    String(courseCondition) === '2';

  const isOld =
    commissionContractInfo?.['vcm_commission_contract_applicable_sets']?.[
      applicableIndex
    ];
  const { fields: sets } = useFieldArray({
    control,
    name: `applicable_sets.${applicableIndex}.sets`,
  });
  return (
    <div
      key={applicableSet.id}
      className="commission-set-addon border border-solid border-gray-400 rounded-sm p-4 m-2 w-full"
    >
      {/* Header with Add/Remove buttons */}
      {showConditionalSections && (
        <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 &&
              applicableIndex === applicableSets.length - 1 &&
              isOld === undefined && (
                <Button
                  type="button"
                  className="active-btn hide-widget"
                  onClick={() => removeApplicableSet(applicableIndex)}
                >
                  -
                </Button>
              )}
            {showConditionalSections &&
              applicableIndex === applicableSets.length - 1 && (
                <Button
                  type="button"
                  className="active-btn show-widget"
                  onClick={() =>
                    handleAddApplicableSet(applicableSets, appendApplicableSet)
                  }
                >
                  +
                </Button>
              )}
          </div>
        </div>
      )}

      {/* Main Content */}
      <div className="w-full">
        <div className="flex flex-wrap">
          {/* Hidden ID field */}
          <Controller
            control={control}
            name={`applicable_sets.${applicableIndex}.id`}
            defaultValue={String(applicableSet.id) || ''}
            render={({ field }) => <input type="hidden" {...field} />}
          />

          {/* Students Per Field */}
          <StudentsPerField
            control={control}
            clearErrors={clearErrors}
            applicableIndex={applicableIndex}
            commissionContractInfo={commissionContractInfo}
          />

          {/* No of Instances Field */}
          <NoOfInstancesField
            control={control}
            clearErrors={clearErrors}
            getValues={getValues}
            setValue={setValue}
            applicableIndex={applicableIndex}
            noOfInstances={noOfInstances}
            setNoOfInstances={setNoOfInstances} // Pass the setter function
            commissionContractInfo={commissionContractInfo}
          />
        </div>
      </div>

      {/* Applicable On Section */}
      {showConditionalSections && (
        <ApplicableOnSection
          control={control}
          clearErrors={clearErrors}
          index={applicableIndex}
          campusCondition={campusCondition}
          studyLevelCondition={studyLevelCondition}
          courseCondition={courseCondition}
          campuses={campuses}
          studyLevels={studyLevels}
          studyLevelCoursesList={studyLevelCoursesList}
          onCourseLevelsChange={handleCourseLevelsChange}
          record={
            commissionContractInfo?.[
              'vcm_commission_contract_applicable_sets'
            ]?.[applicableIndex] || {}
          }
        />
      )}

      {/* Sets Section Header */}
      <div className="commission-instance-widget mt-4 mb-4">
        <div className="heading ml-2">Sets</div>
      </div>

      {/* Commission Sets */}
      {sets.map((set: any, setIndex: number) => (
        <CommissionSetCard
          key={set.id || setIndex}
          control={control}
          clearErrors={clearErrors}
          getValues={getValues}
          applicableIndex={applicableIndex}
          setIndex={setIndex}
          set={set}
          isRange={isRange}
          hasBonusByIndex={hasBonusByIndex}
          handleHasBonusChange={handleHasBonusChange}
          handleRemoveSet={handleRemoveSet}
          handleAddSet={handleAddSet}
          noOfInstances={noOfInstances}
          commissionContractInfo={commissionContractInfo}
          hasBonusOptions={hasBonusOptions}
          bonusTypeOptions={bonusTypeOptions}
          commissionTypeOptions={commissionTypeOptions}
          setValue={setValue}
          setsLength={sets.length}
          form={form}
        />
      ))}
    </div>
  );
};

export default ApplicableSetCard;
