import {
  createContext,
  ReactNode,
  useContext,
  useEffect,
  useState,
} from "react";
import { currentUser, logout, User } from "./api";
import { Login } from "./Login";
import Header from "./Header";

export interface SessionProviderProps {
  children: ReactNode;
}

export interface Session {
  user: User | null;
  onLogout: () => void;
}

const sessionContext = createContext<Session>({
  user: null,
  onLogout: () => {},
});

export function SessionProvider(props: SessionProviderProps) {
  const { children } = props;

  const [user, setUser] = useState<User | null>(null);
  const [err, setErr] = useState<unknown>(null);
  const [loading, setLoading] = useState(false);

  function loadUser() {
    setLoading(true);
    currentUser()
      .then((user) => {
        setUser(user);
        setErr(null);
      })
      .catch((err) => {
        setUser(null);
        setErr(err);
      })
      .finally(() => setLoading(false));
  }

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

  function onLogin(user: User) {
    setUser(user);
    setErr(null);
  }

  async function onLogout() {
    try {
      logout();
      setUser(null);
      setErr({ message: "Logged out successfully" });
      console.log("logged out.");
    } catch (e) {
      console.error(e);
      setErr(e);
    }
  }
  console.log("sanity", user);

  let content: ReactNode;
  if (loading || (!err && !user))
    content = (
      <>
        <Header />
        <span className="loader" />
      </>
    );
  else if (err) {
    content = <Login onLogin={onLogin} />;
  } else
    content = (
      <sessionContext.Provider value={{ user, onLogout }}>
        {children}
      </sessionContext.Provider>
    );

  return content;
}

export function useSession() {
  return useContext(sessionContext);
}
