import React, { createContext, useState, useEffect, useContext } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { SessionContextProviderProps } from "../interfaces/ContextInterface";

interface SessionContextType {
  isLoggedIn: boolean;
  login: () => void;
  logout: () => void;
}

const SessionContext = createContext<SessionContextType | undefined>(undefined);

// Keep entries lowercase; we'll compare with a normalized lowercase pathname
const allowedPathsWhenLoggedOut = new Set([
  "/reset-password",
  "/signup",
  "/clientonboard",
  "/",
  "/change-password",
  "/admin/signup",
  "/admin/changepassword",
  "/admin/profile",
  "/admin/login",
  "/admin/resetpassword",
  "/auth-callback",
  "/verification-callback",
  "/kyc",
  "/didit-verification",
]);

const SessionContextProvider: React.FC<SessionContextProviderProps> = ({
  children,
}) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const loggedIn = sessionStorage.getItem("isLoggedIn") === "true";
    const normalizePath = (p: string) => {
      const trimmed = p.replace(/\/+$/, "");
      return trimmed === "" ? "/" : trimmed;
    };
    const pathKey = normalizePath(location.pathname).toLowerCase();
    if (allowedPathsWhenLoggedOut.has(pathKey)) {
      sessionStorage.setItem("isLoggedIn", "false");
      setIsLoggedIn(false);
    } else {
      setIsLoggedIn(loggedIn);
    }
  }, [location.pathname]);

  const login = () => {
    sessionStorage.setItem("isLoggedIn", "true");
    setIsLoggedIn(true);
  };

  const logout = () => {
    sessionStorage.setItem("isLoggedIn", "false");
    setIsLoggedIn(false);
    navigate("/", { replace: true });
  };

  return (
    <SessionContext.Provider value={{ isLoggedIn, login, logout }}>
      {children}
    </SessionContext.Provider>
  );
};

const useSession = (): SessionContextType => {
  const context = useContext(SessionContext);
  if (!context) {
    throw new Error("ERROR_MESSAGES.SESSION_ERROR");
  }
  return context;
};

export { SessionContextProvider, useSession };
