import React from 'react';
import {
  Control,
  UseFormClearErrors,
  UseFormGetValues,
  UseFormSetValue,
} from 'react-hook-form';
import {
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

interface NoOfInstancesFieldProps {
  control: Control<any>;
  clearErrors: UseFormClearErrors<any>;
  getValues: UseFormGetValues<any>;
  setValue: UseFormSetValue<any>;
  applicableIndex: number;
  noOfInstances: Record<string, number>;
  setNoOfInstances: (
    value: React.SetStateAction<Record<string, number>>,
  ) => void;
  commissionContractInfo?: any;
}

const COMMISSION_INSTANCE_OPTIONS = [
  { value: '1', label: '1' },
  { value: '2', label: '2' },
  { value: '3', label: '3' },
  { value: '4', label: '4' },
  { value: '5', label: '5' },
  { value: '6', label: '6' },
  { value: '7', label: '7' },
  { value: '8', label: '8' },
];

const NoOfInstancesField: React.FC<NoOfInstancesFieldProps> = ({
  control,
  clearErrors,
  getValues,
  setValue,
  applicableIndex,
  noOfInstances,
  setNoOfInstances,
  commissionContractInfo,
}) => {
  const handleValueChange = (value: string, field: any) => {
    const count = parseInt(value, 10);
    const key = `${applicableIndex}`;

    field.onChange(String(value));
    clearErrors(`applicable_sets.${applicableIndex}.no_of_instances`);

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

    // Get all sets in this applicable set
    const sets = getValues(`applicable_sets.${applicableIndex}.sets`) || [];

    // For each set, create exactly 'count' number of instances
    sets.forEach((_: any, setIndex: number) => {
      // Get existing instances to preserve filled data where possible
      const existingInstances =
        getValues(
          `applicable_sets.${applicableIndex}.sets.${setIndex}.instances`,
        ) || [];

      // Create new instances array with exact count
      const newInstances = Array.from({ length: count }, (_, i) => {
        // Preserve existing data if available, otherwise create empty
        return (
          existingInstances[i] || {
            id: '',
            instance: String(i + 1),
            commission_type: '',
            commission_amount: '',
          }
        );
      });

      // Set the new instances array
      setValue(
        `applicable_sets.${applicableIndex}.sets.${setIndex}.instances`,
        newInstances,
        { shouldValidate: false },
      );

      // Clear all errors for this set's instances
      clearErrors(
        `applicable_sets.${applicableIndex}.sets.${setIndex}.instances`,
      );
    });
  };

  const getCurrentNoOfInstances = (): number => {
    return (
      commissionContractInfo?.['vcm_commission_contract_applicable_sets']?.[
        applicableIndex
      ]?.['no_of_instances'] || 0
    );
  };

  const isOptionDisabled = (optionValue: string): boolean => {
    const currentValue = getCurrentNoOfInstances();
    return parseInt(optionValue, 10) < currentValue;
  };

  return (
    <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={String(field.value || '')}
            onValueChange={(value) => handleValueChange(value, field)}
          >
            <SelectTrigger>
              <SelectValue placeholder="Select Commission Instance" />
            </SelectTrigger>
            <SelectContent className="z-[9999]">
              {COMMISSION_INSTANCE_OPTIONS.map((item) => (
                <SelectItem
                  key={item.value}
                  value={item.value}
                  disabled={isOptionDisabled(item.value)}
                >
                  {item.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <FormMessage />
        </FormItem>
      )}
    />
  );
};

export default NoOfInstancesField;
