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

import { type FormInputSearchProps } from './types';
import InputSearch from '.';

export const FormInputSearch: FC<FormInputSearchProps> = ({
  name,
  inputProps: { onChange: onChangeProp = () => null, ...inputProps } = {},
  rules,
}) => {
  const handleChange =
    (callback: (value: string) => void) => (value: string) => {
      callback(value);
      onChangeProp(value);
    };

  return (
    <Controller
      render={({
        field: { ref, onBlur, onChange, ...field },
        fieldState: { error },
      }) => (
        <InputSearch
          {...field}
          {...inputProps}
          onChange={handleChange(onChange)}
          inputRef={ref}
          error={!!error}
          errorText={error?.message}
        />
      )}
      name={name}
      rules={rules}
    />
  );
};

export type { FormInputSearchProps };

export default FormInputSearch;
