import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import { useAuth } from './AuthContext';
import { usePermissions } from '@/hooks/usePermissions';

interface AdminContextType {
  // Admin-specific state
  isAdminMode: boolean;
  adminStats: {
    pendingVerifications: number;
    pendingTranslations: number;
    systemAlerts: number;
  } | null;
  refreshAdminStats: () => Promise<void>;
  isLoadingStats: boolean;
}

const AdminContext = createContext<AdminContextType | undefined>(undefined);

export const useAdmin = () => {
  const context = useContext(AdminContext);
  if (context === undefined) {
    throw new Error('useAdmin must be used within an AdminProvider');
  }
  return context;
};

interface AdminProviderProps {
  children: React.ReactNode;
}

/**
 * Admin context provider for admin-specific state and functionality
 */
export const AdminProvider = ({ children }: AdminProviderProps) => {
  const { isAuthenticated } = useAuth();
  const { isAdmin } = usePermissions();
  const [adminStats, setAdminStats] = useState<AdminContextType['adminStats']>(null);
  const [isLoadingStats, setIsLoadingStats] = useState(false);

  const isAdminMode = isAuthenticated && isAdmin;

  const refreshAdminStats = useCallback(async () => {
    if (!isAdminMode) {
      setAdminStats(null);
      return;
    }

    setIsLoadingStats(true);
    try {
      // TODO: Replace with actual API call
      // const stats = await fetchAdminStats();
      // For now, using mock data
      const stats = {
        pendingVerifications: 0,
        pendingTranslations: 0,
        systemAlerts: 0,
      };
      setAdminStats(stats);
    } catch (error) {
      console.error('Failed to fetch admin stats:', error);
    } finally {
      setIsLoadingStats(false);
    }
  }, [isAdminMode]);

  useEffect(() => {
    if (isAdminMode) {
      refreshAdminStats();
      // Refresh stats every 30 seconds
      const interval = setInterval(refreshAdminStats, 30000);
      return () => clearInterval(interval);
    }
  }, [isAdminMode, refreshAdminStats]);

  const value: AdminContextType = {
    isAdminMode,
    adminStats,
    refreshAdminStats,
    isLoadingStats,
  };

  return <AdminContext.Provider value={value}>{children}</AdminContext.Provider>;
};
