import React, { createContext, useContext, useEffect, useState } from "react";
import Cookies from "js-cookie";
import { setToken } from "../utils/baseRequest";
import storage from "../utils/storage";

export type AuthContextProps = {
  isLogin: boolean;
  ready: boolean;
  setLogin: (token: string) => void;
  setLogout: () => void;
};

export const AuthContext = createContext<AuthContextProps>({
  isLogin: false,
  ready: false,
  setLogin: () => null,
  setLogout: () => null,
});

export type AuthProviderProps = {
  children: JSX.Element;
};

function AuthProvider({ children }: AuthProviderProps) {
  const [{ isLogin, ready }, setAuth] = useState({
    isLogin: false,
    ready: false,
  });

  useEffect(() => {
    const token = Cookies.get("token");
    console.log(token);

    if (!!token && !isLogin) {
      setToken(token);
      setAuth({
        isLogin: true,
        ready: true,
      });
    }
  }, []);

  const setLogin = (token: string) =>
    new Promise((resolve) => {
      Cookies.set("token", token);
      setToken(token);
      setAuth((prevState) => ({ ...prevState, isLogin: true }));
      setTimeout(resolve, 0);
    });

  const setLogout = () => {
    Cookies.remove("token");
    storage.remove("user");
    storage.remove("userType");
    setAuth(() => ({ isLogin: false, ready: true }));
  };
  return (
    <AuthContext.Provider
      value={{
        isLogin,
        ready,
        setLogin,
        setLogout,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = (guard = true) => {
  // const router = useRouter();
  const { isLogin, ready, ...rest } = useContext(AuthContext);

  useEffect(() => {
    if (guard && !Cookies.get("token")) {
      // router?.push("/");
    }
  });

  useEffect(() => {
    if (guard && ready && !isLogin) {
      // router.push('/');
    }
  }, [ready]);

  return { isLogin, ready, ...rest };
};

export default AuthProvider;
