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

interface StudentsPerFieldProps {
  control: Control<any>;
  clearErrors: UseFormClearErrors<any>;
  applicableIndex: number;
  commissionContractInfo?: UnknownRecord;
}

const StudentsPerField: React.FC<StudentsPerFieldProps> = ({
  control,
  clearErrors,
  applicableIndex,
  commissionContractInfo,
}) => {
  const getDefaultValue = (): string => {
    return String(
      commissionContractInfo?.['vcm_commission_contract_applicable_sets']?.[
        applicableIndex
      ]?.['students_per'] || '',
    );
  };

  const handleValueChange = (value: string, field: any) => {
    field.onChange(String(value));
    clearErrors(`applicable_sets.${applicableIndex}.students_per`);
  };

  return (
    <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
            defaultValue={getDefaultValue()}
            value={String(field.value)}
            onValueChange={(value) => handleValueChange(value, field)}
          >
            <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>
      )}
    />
  );
};

export default StudentsPerField;
