import { SubmitHandler, useForm } from "react-hook-form"
import { LoginFormValues } from "../infraestructure/entities/login_form_values"
import { LoginRepositoryProd } from "../data/repositories/prod/login_repository";
import { LoginDatasourceProd } from "../data/datasources/prod/login_datasource";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../context/auth_context";
const loginDatasource = new LoginDatasourceProd();
const loginRepository = new LoginRepositoryProd(loginDatasource);

export const useLogin = () => {
  const {login, user} = useAuth();
  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    setError,
    formState: {errors},
  } = useForm<LoginFormValues>();

  const onSubmit: SubmitHandler<LoginFormValues> = (data: LoginFormValues) => {
    const authenticate = async () => {
      try{
        const {user, token } = await loginRepository.getToken(data);
        await login(user, token);
        navigate("/");
      }catch(error: any){

      }
    }
    authenticate();
  }

  useEffect(() => {
    if(user) {
      navigate("/");
    }
  }, []);

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