import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  ReactNode,
} from "react";
import Cookies from "js-cookie";
import { MeDto } from "@/shared/dto/user/meDto";
import { useAuth as useFreightAuth } from "@/auth/useAuth";

// ----- TYPES -----
export interface Role {
  id: string;
  key: string;
}

interface AuthContextType {
  user: MeDto | null;
  loading: boolean;
  setUser: (user: MeDto | null) => void;
  selectedPositionId: string | null;
  setSelectedPositionId: (id: string | null) => void;
  showOtpModal: boolean;
  setShowOtpModal: (show: boolean) => void;
  rememberMePreference: boolean;
  setRememberMePreference: (rememberMe: boolean) => void;
}

// ----- CONTEXT -----
const AuthContext = createContext<AuthContextType>({
  user: null,
  loading: true,
  setUser: () => {},
  selectedPositionId: null,
  setSelectedPositionId: () => {},
  showOtpModal: false,
  setShowOtpModal: () => {},
  rememberMePreference: false,
  setRememberMePreference: () => {},
});

// ----- PROVIDER -----
export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<MeDto | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedPositionId, setSelectedPositionId] = useState<string | null>(
    null
  );
  const [showOtpModal, setShowOtpModal] = useState(false);
  const [rememberMePreference, setRememberMePreference] = useState(false);

  // Bridge to the freight session: this provider renders inside the freight
  // AuthProvider, so the real signed-in user is available here. The vendored IAM
  // code (AppMenuTabs, pages) reads `user` from this context — feed it the
  // freight user so it isn't null. Falls back to the legacy auth-user cookie.
  const { user: freightUser } = useFreightAuth();

  useEffect(() => {
    const positionId = Cookies.get("selected-position-id");
    if (positionId) setSelectedPositionId(positionId);

    if (freightUser) {
      setUser(freightUser as unknown as MeDto);
      setLoading(false);
      return;
    }

    const cookieUser = Cookies.get("auth-user");
    if (cookieUser) {
      try {
        setUser(JSON.parse(cookieUser));
      } catch (e) {
        console.error("Invalid user cookie");
      }
    }
    setLoading(false);
  }, [freightUser]);
  // useEffect(() => {
  //   sessionStorage.setItem("tabActive", "true");

  //   const handleTabClose = (event: BeforeUnloadEvent) => {
  //     const [nav] = performance.getEntriesByType(
  //       "navigation"
  //     ) as PerformanceNavigationTiming[];

  //     // If page was reloaded, don't remove tokens
  //     if (nav && nav.type === "reload") return;

  //     const rememberMe = JSON.parse(
  //       localStorage.getItem("rememberMe") || "false"
  //     );
  //     if (!rememberMe) {
  //       Cookies.remove("auth-token");
  //       Cookies.remove("refresh-token");
  //       sessionStorage.removeItem("auth-token");
  //       setUser(null);
  //     }
  //   };

  //   window.addEventListener("beforeunload", handleTabClose);
  //   return () => window.removeEventListener("beforeunload", handleTabClose);
  // }, []);

  useEffect(() => {
    if (selectedPositionId) {
      Cookies.set("selected-position-id", selectedPositionId);
    }
  }, [selectedPositionId]);

  return (
    <AuthContext.Provider
      value={{
        user,
        loading,
        setUser,
        selectedPositionId,
        setSelectedPositionId,
        showOtpModal,
        setShowOtpModal,
        rememberMePreference,
        setRememberMePreference,
      }}>
      {children}
    </AuthContext.Provider>
  );
};

// ----- HOOK -----
export const useAuth = () => useContext(AuthContext);
