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

export interface UseInputControllerProps {
  name: string;
  showSuccess?: boolean;
  helperText?: string | string[];
  defaultValue?: any;
}

export const useInputController = ({
  name,
  showSuccess,
  helperText,
  defaultValue,
}: UseInputControllerProps) => {
  const {field, fieldState} = useController({name, defaultValue});

  const helper = fieldState.error?.message || helperText;
  const isError = !!fieldState.error?.message;
  const isSuccess =
    showSuccess && fieldState.isDirty && !isError && field.value !== undefined;

  return {
    helper,
    isError,
    isSuccess,
    onBlur: field.onBlur,
    onChange: field.onChange,
    value: field.value,
  };
};
