import { useState, useCallback } from 'react';

interface IForm {
  name: string;
  email: string
}

export default function useFormWithValidation() {
  const [values, setValues] = useState<IForm>({
    name: "",
    email: ""
  });
  const [errors, setErrors] = useState<IForm>({
    name: "",
    email: ""
  });
  const [isValid, setIsValid] = useState<boolean>(false);

  const handleChangeState = (event: React.ChangeEvent<HTMLInputElement>) => {
    const target = event.target;
    const name = target.name;
    const value = target.value;
    setValues({ ...values, [name]: value });
    setErrors({ ...errors, [name]: target.validationMessage });
    setIsValid(target.closest("form").checkValidity());
  };

  const resetForm = useCallback(
    (newValues = { name: "", email: "" }, newIsValid = false) => {
      setValues(newValues);
      setErrors(newValues);
      setIsValid(newIsValid);
    },
    [setValues, setErrors, setIsValid]
  );

  return { values, handleChangeState, errors, isValid, resetForm };
}