"use client";
import { GET_USER_ROUTE } from "@/core/utils/routes";
import axios from "axios";
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useReducer,
  useState,
} from "react";

const initAuth = {
  initAuthState: false,
  isAuth: false,
  user: {},
};

const authReducer = (state, action) => {
  switch (action.type) {
    case "CLEAR_USER":
      return { ...state, user: {} };
    case "CHANGE_USER":
      return { ...state, user: action.user };
    case "CHANGE_AUTH_STATE":
      return { ...state, isAuth: action.isAuth };
    case "CHANGE_INIT_AUTH":
      return { ...state, initAuthState: action.initAuthState };
    default:
      return state;
  }
};

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [errorState, setErrorState] = useState({ status: null, message: "" });
  const [state, dispatch] = useReducer(authReducer, initAuth);

  const clearUser = useCallback(() => {
    dispatch({ type: "CLEAR_USER" });
  }, []);

  const changeUser = useCallback((user) => {
    dispatch({ type: "CHANGE_USER", user });
  }, []);

  const changeAuthState = useCallback((isAuth) => {
    dispatch({ type: "CHANGE_AUTH_STATE", isAuth });
  }, []);

  const changeInitAuth = useCallback((initAuthState) => {
    dispatch({ type: "CHANGE_INIT_AUTH", initAuthState });
  }, []);

  const logout = () => {
    clearUser();
    changeAuthState(false);
    changeInitAuth(true);
  };

  const getUser = useCallback(async () => {
    try {
      const { data } = await axios.get(GET_USER_ROUTE, {
        withCredentials: true,
      });
      changeUser(data.data);
      changeAuthState(true);
      changeInitAuth(true);
      setErrorState(false);
    } catch (error) {
      if (error.response && error.response.status === 401) {
        clearUser();
        changeAuthState(false);
        changeInitAuth(true);
        return;
      }
      let status =
        error.response && error.response.status
          ? error.response.status
          : "نامشخص";
      setErrorState({
        status,
        message: " مشکلی در احراز هویت رخ داده است . دقایقی بعد امتحان کنید!!!",
      });
    }
  }, [clearUser, changeUser, changeAuthState, changeInitAuth]);

  useEffect(() => {
    getUser();
  }, []);

  return (
    <AuthContext.Provider
      value={{
        user: state.user,
        isAuth: state.isAuth,
        initAuthState: state.initAuthState,
        getUser,
        logout,
        errorState,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);
