import { set, useForm } from "react-hook-form";
import { useAuth } from "../contexts/auth_context";
import { Navigator, Redirect, router } from "expo-router";
import { useDataContext } from "../../common/contexts/data_context";
import { useState } from "react";
import { ApiRequestStatus } from "../../common/const/api_request_states";
import { ApiResponseError } from "../errors/api_response_error";

export type LoginFormValues = {
  email: string;
  password: string;
};

export const useLoggin = () => {
  const {
    control,
    handleSubmit,
    formState: { errors },
    setError,
  } = useForm<LoginFormValues>();
  const { authRepository } = useDataContext();
  const { login } = useAuth();
  const [requestStatus, setRequestStatus] = useState(ApiRequestStatus.IDLE);
  const [isErrorModalVisible, setIsErrorModalVisible] = useState(false);

  const setLoading = async () => {
    setRequestStatus(ApiRequestStatus.LOADING);
  };

  const validSubmit = async (data: LoginFormValues) => {
    try {
      await setLoading();
      const { user, token } = await authRepository!.login(
        data.email,
        data.password
      );
      await login(user, token);
      setRequestStatus(ApiRequestStatus.SUCCESS);
      router.replace("/(tabs)");
    } catch (error: any) {
      const { status } = error as ApiResponseError;
      switch (status) {
        case 401:
          setError("email", {
            type: "manual",
            message: "Invalid email or password",
          });
          setError("password", {
            type: "manual",
            message: "Invalid email or password",
          });
          setRequestStatus(ApiRequestStatus.ERROR);
          break;
        default:
          setIsErrorModalVisible(true);
          setRequestStatus(ApiRequestStatus.ERROR);
          break;
      }
    }
  };

  const closeErrorModal = () => {
    setIsErrorModalVisible(false);
  };

  const invalidSubmit = (errors: any) => {
    console.log(errors);
  };

  const onSubmit = async () => {
    await handleSubmit(validSubmit, invalidSubmit)();
  };

  return {
    control,
    onSubmit,
    closeErrorModal,
    requestStatus,
    isErrorModalVisible,
  };
};
