import React from 'react';
import {
  Control,
  UseFormClearErrors,
  UseFormGetValues,
  Controller,
  UseFormSetValue,
} from 'react-hook-form';
import {
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormControl,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import StudentRangeFields from './StudentRangeFields';
import BonusFields from './BonusFields';
import CommissionInstancesSection from './CommissionInstancesSection';
import { UnknownRecord } from '@/types';

interface CommissionSetCardProps {
  control: Control<any>;
  clearErrors: UseFormClearErrors<any>;
  getValues: UseFormGetValues<any>;
  applicableIndex: number;
  setIndex: number;
  set: any;
  isRange: boolean;
  hasBonusByIndex: Record<string, boolean>;
  handleHasBonusChange: (
    applicableIndex: number,
    setIndex: number,
    value: string,
  ) => void;
  handleRemoveSet: (applicableIndex: number, setIndex: number) => void;
  handleAddSet: (applicableIndex: number, setIndex: number) => void;
  noOfInstances: Record<string, number>;
  commissionContractInfo?: UnknownRecord;
  hasBonusOptions: Array<{ id: number | string; name: string }>;
  bonusTypeOptions: Array<{ id: number | string; name: string }>;
  commissionTypeOptions: Array<{ id: number | string; name: string }>;
  setValue: UseFormSetValue<any>;
  setsLength: number;
  form: any;
}

const CommissionSetCard: React.FC<CommissionSetCardProps> = ({
  control,
  clearErrors,
  getValues,
  applicableIndex,
  setIndex,
  set,
  isRange,
  hasBonusByIndex,
  handleHasBonusChange,
  handleRemoveSet,
  handleAddSet,
  noOfInstances,
  commissionContractInfo,
  hasBonusOptions,
  bonusTypeOptions,
  commissionTypeOptions,
  setValue,
  setsLength,
  form,
}) => {
  return (
    <div
      key={setIndex}
      className="border border-solid border-gray-200 rounded-sm p-4 m-2 w-full"
    >
      {/* Header with actions */}
      <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 === setsLength - 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">
          {/* Hidden ID field */}
          <Controller
            control={control}
            name={`applicable_sets.${applicableIndex}.sets.${setIndex}.id`}
            defaultValue={String(set.id || '')}
            render={({ field }) => <input type="hidden" {...field} />}
          />

          {/* Set Name Field */}
          <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="Set Name"
                    {...field}
                    onChange={(e) => {
                      field.onChange(e.target.value);
                      clearErrors(
                        `applicable_sets.${applicableIndex}.sets.${setIndex}.set_name`,
                      );
                    }}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* Student Range Fields */}
          {isRange && (
            <StudentRangeFields
              control={control}
              clearErrors={clearErrors}
              applicableIndex={applicableIndex}
              setIndex={setIndex}
              isRange={isRange}
            />
          )}

          {/* Bonus Fields */}
          <BonusFields
            control={control}
            clearErrors={clearErrors}
            applicableIndex={applicableIndex}
            setIndex={setIndex}
            hasBonus={hasBonusByIndex[`${applicableIndex}-${setIndex}`]}
            onHasBonusChange={handleHasBonusChange}
            hasBonusOptions={hasBonusOptions}
            bonusTypeOptions={bonusTypeOptions}
            record={
              commissionContractInfo?.[
                'vcm_commission_contract_applicable_sets'
              ]?.[applicableIndex]?.['vcm_commission_contract_sets']?.[
                setIndex
              ] || {}
            }
            getValues={getValues}
            setValue={setValue}
          />
        </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={commissionTypeOptions}
            getValues={getValues}
            setValue={setValue}
            form={form}
          />
        )}
      </div>
    </div>
  );
};

export default CommissionSetCard;
