import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { Redirect } from 'react-router-dom';
import authApi from "../apis/auth.api";
import catchErrors from './catchErrors';

const AuthContext = createContext({
  error: "",
  user: { id: "", role: "user", name: "" },
  setUser: () => { },
  login: () => Promise.resolve(false),
  logout: () => { },
  catchErrorAuth: (error, displayError) => { },
});

const AuthProvider = ({ children }) => {
  const [error, setError] = useState("");
  const [user, setUser] = useState({ id: "", role: "user", name: "" });
  const getUser = async () => {
    const { id, role, userName } = await authApi.getUser();
    const user = { id: id, role: role, name: userName };
    setUser(user);
  }
  useEffect(() => {
    getUser();
  }, []);

  const login = useCallback(async (data) => {
    try {
      setError("");
      const user = await authApi.login(data);
      console.log('user in context', user)
      setUser(user);
      console.log('setUser 결과', user)
      return true;
    } catch (error) {
      catchErrors(error, setError);
      return false;
    }
  }, []);

  const logout = useCallback(async () => {
    try {
      setError("");
      const user = await authApi.logout();
      setUser(user);
      alert("로그아웃 되었습니다.");
    } catch (error) {
      catchErrors(error, setError);
    }
  }, []);

  const catchErrorAuth = useCallback(async (error, displayError) => {
    let errMsg;
    if (error.response) {
      if (typeof error.response.data === "string") {
        errMsg = error.response.data;
        console.log('Error response:', errMsg);
      } else {
        const { data } = error.response;
        if (data.redirectUrl) {
          errMsg = data.message;
          console.log('Error response with redirected message:', errMsg);
          return await logout();
        }
      }
    } else if (error.request) {
      errMsg = error.request;
      console.log('Error request:', errMsg);
    } else {
      errMsg = error.message;
      console.log("Error message:", errMsg)
    }
    displayError(errMsg);
  }, []);

  return (
    <AuthContext.Provider value={{ error, user, setUser, login, logout, catchErrorAuth }} >
      {children}
    </AuthContext.Provider>
  );
};

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

export { AuthProvider, useAuth };

