"use client";

import React, { ReactNode, createContext, useEffect, useState } from "react";
import Cookies from "js-cookie";
import { User } from "../apiSchema/user.schema";
import { getEduConnectAccessToken, removeEduConnectAccessToken } from "../token.helper";
import { usePathname, useRouter } from "next/navigation";
import { privateRoutes, routes } from "@/lib/routes";

interface AuthContextProps {
  user: User | null;
  loading: boolean;
  fetchUser: (token: string) => void;
  logout: () => void;
}

interface AuthProviderProps {
  children: ReactNode;
}

const AuthContext = createContext<AuthContextProps>({
  user: null,
  loading: true,
  fetchUser: () => {},
  logout: () => {},
});

const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  

  const router = useRouter()
  const pathname = usePathname()
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchUser = async () => {
    
    try {
      // Fetch user data
      const userResponse = await fetch(`${process.env.NEXT_PUBLIC_EDU_CONNECT_HOST}/api/profile/me`, {
        headers: {
          Authorization: `Bearer ${getEduConnectAccessToken()}`,
          Accept: "Application/json",
        },
      });

      if(userResponse.status == 401){
        removeEduConnectAccessToken();
        if(privateRoutes.includes(pathname)) router.replace(routes.INDEX_PAGE)
        return
      }

      const userData = await userResponse.json();
      setUser(userData.profile);
    } catch (error) {
      console.error("Fetch error:", error);
      removeEduConnectAccessToken();
      // 401 
    } finally {
      setLoading(false); 
    }
  };

  useEffect(() => {
    if (!user) {
      fetchUser();
    }
  }, []);


  const logout = async () => {
    try {
      await fetch(`${process.env.NEXT_PUBLIC_IDP_HOST}/api/logout`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${getEduConnectAccessToken()}`,
        },
      });
      fetchUser();
    } catch (error) {
      console.error("Logout error:", error);
    } finally {
      Cookies.remove("EDU_CONNECT_ACCESS_TOKEN", { domain: process.env.APP_DOMAIN });
      setUser(null);
    }
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        loading: !user && loading,
        fetchUser: fetchUser,
        logout,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export { AuthContext, AuthProvider };