"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useState,
  type ReactNode,
} from "react";
import { getCurrentUserAction } from "@/features/users/actions/user-actions";
import type { User } from "@/core/api";

interface AdminAuthContextValue {
  currentUser: User | null;
  isLoading: boolean;
  refetch: () => Promise<void>;
}

const AdminAuthContext = createContext<AdminAuthContextValue | null>(null);

/**
 * Fetches ADMIN_PROFILE once when entering admin area and provides current user to all admin pages.
 * Use this so Dashboard, Customers, and Agents do not each call ADMIN_PROFILE.
 */
export function AdminAuthProvider({ children }: { children: ReactNode }) {
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const fetchUser = useCallback(async () => {
    try {
      const result = await getCurrentUserAction();
      if (result.success && result.data) {
        setCurrentUser(result.data as User);
      } else {
        setCurrentUser(null);
      }
    } catch {
      setCurrentUser(null);
    } finally {
      setIsLoading(false);
    }
  }, []);

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

  const value: AdminAuthContextValue = {
    currentUser,
    isLoading,
    refetch: fetchUser,
  };

  return (
    <AdminAuthContext.Provider value={value}>
      {children}
    </AdminAuthContext.Provider>
  );
}

export function useAdminAuth() {
  const ctx = useContext(AdminAuthContext);
  if (!ctx) {
    throw new Error("useAdminAuth must be used within AdminAuthProvider");
  }
  return ctx;
}
