import { useRef, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Shield, Users, FileText, Flag, AlertCircle, RefreshCw } from 'lucide-react';
import { useUserRole } from '@/hooks/useUserRole';
import { useAuth } from '@/hooks/useAuth';
import { useIsMobile } from '@/hooks/use-mobile';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ModerationQueue, ModerationQueueRef } from '@/components/moderation/ModerationQueue';
import { ReportsQueue, ReportsQueueRef } from '@/components/moderation/ReportsQueue';
import { UserManagement } from '@/components/admin/UserManagement';
import { AdminHeader } from '@/components/layout/AdminHeader';
import { useModerationStats } from '@/hooks/useModerationStats';
import { useAdminSettings } from '@/hooks/useAdminSettings';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';

export default function Admin() {
  useDocumentTitle('Admin Panel');
  const isMobile = useIsMobile();
  const { user, loading: authLoading } = useAuth();
  const { isModerator, loading: roleLoading } = useUserRole();
  const navigate = useNavigate();
  const moderationQueueRef = useRef<ModerationQueueRef>(null);
  const reportsQueueRef = useRef<ReportsQueueRef>(null);
  
  // Get admin settings for polling configuration
  const { 
    getAdminPanelRefreshMode, 
    getAdminPanelPollInterval,
    isLoading: settingsLoading 
  } = useAdminSettings();
  
  const refreshMode = getAdminPanelRefreshMode();
  const pollInterval = getAdminPanelPollInterval();
  
  // Use stats hook with configurable polling
  const { stats, refresh: refreshStats, lastUpdated } = useModerationStats({
    enabled: !!user && !authLoading && !roleLoading && isModerator(),
    pollingEnabled: refreshMode === 'auto',
    pollingInterval: pollInterval,
  });

  const handleRefresh = useCallback(() => {
    moderationQueueRef.current?.refresh();
    reportsQueueRef.current?.refresh();
    refreshStats();
  }, [refreshStats]);

  useEffect(() => {
    if (!authLoading && !roleLoading) {
      if (!user) {
        navigate('/auth');
        return;
      }
      
      if (!isModerator()) {
        navigate('/');
        return;
      }
    }
  }, [user, authLoading, roleLoading, navigate, isModerator]);

  if (authLoading || roleLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
            <p className="text-muted-foreground">Loading admin panel...</p>
          </div>
        </div>
      </div>
    );
  }

  if (!user || !isModerator()) {
    return null;
  }

  return (
    <>
      <AdminHeader onRefresh={handleRefresh} />
      <div className="container mx-auto px-4 py-8">
      <div className="space-y-4 mb-8">
        {/* Refresh status indicator */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <RefreshCw className="w-4 h-4" />
            {refreshMode === 'auto' ? (
              <span>Auto-refresh: every {pollInterval / 1000}s</span>
            ) : (
              <span>Manual refresh only</span>
            )}
            {lastUpdated && (
              <span className="text-xs">
                • Last updated: {lastUpdated.toLocaleTimeString()}
              </span>
            )}
          </div>
        </div>

        {/* Stats cards */}
        <div className="grid grid-cols-3 gap-3 md:gap-6">
          <Card>
            <CardHeader className="flex flex-col items-center justify-center space-y-0 pb-2 text-center">
              <FileText className="h-4 w-4 text-muted-foreground mb-2" />
              <CardTitle className="text-sm font-medium">Pending Submissions</CardTitle>
            </CardHeader>
            <CardContent className="text-center">
              <div className="text-2xl font-bold">
                {stats.pendingSubmissions}
              </div>
            </CardContent>
          </Card>
          
          <Card>
            <CardHeader className="flex flex-col items-center justify-center space-y-0 pb-2 text-center">
              <Flag className="h-4 w-4 text-muted-foreground mb-2" />
              <CardTitle className="text-sm font-medium">Open Reports</CardTitle>
            </CardHeader>
            <CardContent className="text-center">
              <div className="text-2xl font-bold">
                {stats.openReports}
              </div>
            </CardContent>
          </Card>
          
          <Card>
            <CardHeader className="flex flex-col items-center justify-center space-y-0 pb-2 text-center">
              <AlertCircle className="h-4 w-4 text-muted-foreground mb-2" />
              <CardTitle className="text-sm font-medium">Flagged Content</CardTitle>
            </CardHeader>
            <CardContent className="text-center">
              <div className="text-2xl font-bold">
                {stats.flaggedContent}
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Content Moderation Section */}
      <Card className="mb-8">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="w-5 h-5" />
            Moderation Queue
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Tabs defaultValue="queue" className="space-y-6">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="queue" className="flex items-center gap-2">
                <FileText className="w-4 h-4" />
                {isMobile ? 'Queue' : 'Moderation Queue'}
              </TabsTrigger>
              <TabsTrigger value="reports" className="flex items-center gap-2">
                <Flag className="w-4 h-4" />
                Reports
              </TabsTrigger>
            </TabsList>
            
            <TabsContent value="queue" forceMount={true}>
              <ModerationQueue ref={moderationQueueRef} />
            </TabsContent>
            
            <TabsContent value="reports" forceMount={true}>
              <ReportsQueue ref={reportsQueueRef} />
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>

      {/* User Management Section */}
      <Card className="mb-8">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Users className="w-5 h-5" />
            User Management
          </CardTitle>
        </CardHeader>
        <CardContent>
          <UserManagement />
        </CardContent>
      </Card>
      </div>
    </>
  );
}