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

import { type AutocompleteOption, type FormAutocompleteProps } from './types';
import Autocomplete from '.';

const FormAutocomplete = <
  TValue extends AutocompleteOption = AutocompleteOption,
  TMultiple extends boolean | undefined = false,
>({
  name,
  rules,
  options,
  autocompleteProps,
}: FormAutocompleteProps<TValue, TMultiple>) => {
  return (
    <Controller
      render={({
        field: { ref, ...fieldMethods },
        fieldState: { error, invalid },
      }) => (
        <Autocomplete
          {...fieldMethods}
          {...autocompleteProps}
          fieldRef={ref}
          options={options}
          hasError={invalid}
          helperText={error?.message ?? autocompleteProps?.helperText}
        />
      )}
      name={name}
      rules={rules}
    />
  );
};

export type { FormAutocompleteProps };

export default FormAutocomplete;
