import { FieldValues, SubmitHandler, useForm } from 'react-hook-form';
import { register as registerService, RegisterResponse } from '../../services';
import { toast } from 'react-toastify';

import { PublicRoutes } from '../../config/routes';
import { useNavigate } from 'react-router-dom';

interface Inputs extends FieldValues {
  email: string;
  password: string;
}

const useRegister = () => {
  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Inputs>();

  const onSubmit: SubmitHandler<Inputs> = async (data) => {
    const response: RegisterResponse = await registerService(
      data.email,
      data.password,
      data.name
    );

    if (response.code === 500) {
      toast.error('Server error');
    }

    if (response.code !== 200) {
      const errorMessages = [];

      if (response.data?.data?.password?.message) {
        errorMessages.push(`Password: ${response.data.data.password.message}`);
      }
      if (response.data?.data?.email?.message) {
        errorMessages.push(`Email: ${response.data.data.email.message}`);
      }
      if (response.data?.data?.name?.message) {
        errorMessages.push(`Name: ${response.data.data.name.message}`);
      }

      const errorMessage = errorMessages.join(' | ');
      toast.error(errorMessage);
    }

    if (response.code === 200) {
      toast.info(response.message);
      navigate(PublicRoutes.LOGIN, {
        replace: true,
      });
    }
  };

  return {
    onSubmit,
    register,
    handleSubmit,
    errors,
  };
};

export default useRegister;
