import { Controller, useFormContext } from 'react-hook-form';

import { type FormIndividualSelectionProps } from './types';
import IndividualSelection from '.';

const FormIndividualSelection = ({
  name,
  searchName,
  inputProps,
  valueRules,
  searchRules,
}: FormIndividualSelectionProps) => {
  const { control } = useFormContext();

  return (
    <Controller
      name={name}
      control={control}
      rules={valueRules}
      render={({ field: { value, onChange } }) => (
        <Controller
          name={searchName}
          control={control}
          rules={searchRules}
          render={({ field: { value: searchValue, onChange: onSearch } }) => (
            <IndividualSelection
              {...inputProps}
              value={value}
              onChange={onChange}
              searchValue={searchValue}
              onSearch={onSearch}
            />
          )}
        />
      )}
    />
  );
};

export type { FormIndividualSelectionProps };

export default FormIndividualSelection;
