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

import { type FormInputPasswordProps } from './types';
import InputPassword from '.';

const FormInputPassword = ({
  name,
  inputProps,
  rules,
  customOnChange,
}: FormInputPasswordProps) => {
  const handleChange =
    (callback: (value: string) => void) => (value: string) => {
      callback(value);

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

export type { FormInputPasswordProps };

export default FormInputPassword;
