import { Dispatch, SetStateAction, useState } from 'react';
import { APIErrorType } from '../../api';

type ErrorMessageType = string;
type UseFormErrorMessageReturnType = {
  formErrorMessage: ErrorMessageType;
  setFormError: (error: APIErrorType) => void;
  resetFormErrorMessage: () => void;
  setFormErrorMessage: Dispatch<SetStateAction<ErrorMessageType>>;
};

export function useFormErrorMessage(): UseFormErrorMessageReturnType {
  const [formErrorMessage, setFormErrorMessage] = useState<ErrorMessageType>('');
  const setFormError = (error: APIErrorType) =>
    setFormErrorMessage(error.data.detail || error.data);
  const resetFormErrorMessage = () => setFormErrorMessage('');
  return { formErrorMessage, setFormErrorMessage, setFormError, resetFormErrorMessage };
}
