import { useNavigate } from "react-router-dom";
import { userStateListener } from "../firebase";
import { createContext, useState, useEffect } from "react";

export const AuthContext = createContext({
  currentUserEmail: undefined,
  currentUserCreatedAt: undefined
});

export const AuthProvider = ({ children, history }) => {
  const [currentUser, setCurrentUser] = useState({
    currentUserEmail: undefined,
    currentUserCreatedAt: undefined
  });
  const navigate = useNavigate();

  useEffect(() => {
    const unsubscribe = userStateListener((user) => {
      const token = user?.accessToken;
      if (token) {
        window.sessionStorage.setItem("token", token);
      } else {
        window.sessionStorage.removeItem("token");
      }
      if (!user) {
        setCurrentUser({
          currentUserEmail: null,
          currentUserCreatedAt: undefined
        });
      } else {
        let createdAt = new Date(parseInt(user.metadata.createdAt, 10));
        if (isNaN(createdAt)) {
          createdAt = undefined;
        }
        setCurrentUser({
          currentUserEmail: user.email,
          currentUserCreatedAt: createdAt
        });
      }
    });
    return unsubscribe;
  }, [navigate]);

  return <AuthContext.Provider value={currentUser}>{children}</AuthContext.Provider>;
};
