import { FieldValues, SubmitHandler, useForm } from 'react-hook-form';
import { login, LoginResponse } from '../../services';
import { toast } from 'react-toastify';
import { PrivateRoutes } from '../../config/routes';
import { useNavigate } from 'react-router-dom';

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

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

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

    if (response.status === 200) {
      toast.success('Login successful');

      navigate(PrivateRoutes.DASHBOARD, {
        replace: true,
      });
    } else {
      toast.error('Login failed');
    }
  };

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

export default useLogin;
