"use client";

import {
  createContext,
  useContext,
  useEffect,
  useState,
  type ReactNode,
} from "react";
import {
  initKeycloak,
  logout as keycloakLogout,
  getUserInfo,
  isAuthenticated as isKeycloakAuthenticated,
} from "@/lib/keycloak-client";

interface AuthContextType {
  isAuthenticated: boolean;
  isLoading: boolean;
  userInfo: any;
  logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [userInfo, setUserInfo] = useState<any>(null);

  useEffect(() => {
    let mounted = true;

    async function initAuth() {
      try {
        const authenticated = await initKeycloak();

        if (mounted) {
          setIsAuthenticated(authenticated);
          setIsLoading(false);
          if (authenticated) {
            setUserInfo(getUserInfo());
          }
        }
      } catch (error) {
        console.error("Auth initialization failed:", error);
        if (mounted) {
          setIsLoading(false);
        }
      }
    }

    initAuth();

    return () => {
      mounted = false;
    };
  }, []);

  const handleLogout = async () => {
    await keycloakLogout();
    setIsAuthenticated(false);
    setUserInfo(null);
  };

  return (
    <AuthContext.Provider
      value={{
        isAuthenticated,
        isLoading,
        userInfo,
        logout: handleLogout,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}
