import { useNavigate } from "@solidjs/router";
import { createContext, onMount, Show, useContext } from "solid-js";
import { createStore } from "solid-js/store";
import { UserType } from "supertokens-web-js/recipe/emailpassword";
import AuthLoader from "../components/AuthLoader";
import { currentUser } from "../services/auth.service";

const AuthStateContext = createContext();
const AuthDispatchContext = createContext<any>();

interface InitState {
  isLoading: boolean;
  isAuthenticated: boolean;
  currentUser: UserType | null;
}

const initialState: InitState = {
  isLoading: true,
  isAuthenticated: false,
  currentUser: null,
};

const AuthProvider = (props: any) => {
  const [store, setStore] = createStore(initialState);
  const navigate = useNavigate();

  const loadCurrentUser = async () => {
    const user = await currentUser();
    if (user) {
      setStore("isAuthenticated", true);
      setStore("currentUser", user);
    }
  };

  onMount(async () => {
    await loadCurrentUser();
    setStore("isLoading", false);
  });

  const setCurrentUser = (user?: UserType) => {
    if (user) {
      setStore("isAuthenticated", true);
      setStore("currentUser", user);
    }
  };
  const removeCurrentUser = () => {
    setStore("isAuthenticated", false);
    setStore("currentUser", null);
  };

  return (
    <AuthStateContext.Provider value={store}>
      <AuthDispatchContext.Provider
        value={{
          setCurrentUser,
          removeCurrentUser,
        }}
      >
        <Show when={!store.isLoading} fallback={<AuthLoader />}>
          {props.children}
        </Show>
      </AuthDispatchContext.Provider>
    </AuthStateContext.Provider>
  );
};

export default AuthProvider;
export const useAuthState = () => useContext(AuthStateContext);
export const useAuthDispatch = () => useContext(AuthDispatchContext);
