import { useRef, useEffect, useCallback, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Shield, Users, FileText, Flag, AlertCircle } 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 } from '@/components/moderation/ReportsQueue';
import { UserManagement } from '@/components/admin/UserManagement';
import { AdminHeader } from '@/components/layout/AdminHeader';
import { supabase } from '@/integrations/supabase/client';
import { useRealtimeModerationStats } from '@/hooks/useRealtimeModerationStats';

export default function Admin() {
  const isMobile = useIsMobile();
  const { user, loading: authLoading } = useAuth();
  const { isModerator, loading: roleLoading } = useUserRole();
  const navigate = useNavigate();
  const moderationQueueRef = useRef<ModerationQueueRef>(null);
  
  // Use realtime stats hook for live updates
  const { stats: realtimeStats, refresh: refreshStats } = useRealtimeModerationStats({
    onStatsChange: (newStats) => {
      console.log('Stats updated in real-time:', newStats);
    },
    enabled: !!user && !authLoading && !roleLoading && isModerator(),
  });
  
  const [isFetching, setIsFetching] = useState(false);

  const fetchStats = useCallback(async () => {
    refreshStats();
  }, [refreshStats]);

  const handleRefresh = useCallback(() => {
    moderationQueueRef.current?.refresh();
    fetchStats(); // Also refresh stats
  }, []);

  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="mb-8">
          <p className="text-muted-foreground">
            Manage content moderation and user roles
          </p>
        </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Pending Submissions</CardTitle>
            <FileText className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {realtimeStats.pendingSubmissions}
            </div>
            <p className="text-xs text-muted-foreground">
              Content submissions awaiting moderation
            </p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Open Reports</CardTitle>
            <Flag className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {realtimeStats.openReports}
            </div>
            <p className="text-xs text-muted-foreground">
              User reports to review
            </p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Flagged Content</CardTitle>
            <AlertCircle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {realtimeStats.flaggedContent}
            </div>
            <p className="text-xs text-muted-foreground">
              Auto-flagged items
            </p>
          </CardContent>
        </Card>
      </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>
          <CardDescription>
            Review and moderate pending content submissions and flagged reviews
          </CardDescription>
        </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">
              <ModerationQueue ref={moderationQueueRef} />
            </TabsContent>
            
            <TabsContent value="reports">
              <ReportsQueue />
            </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>
          <CardDescription>
            Manage user profiles and role assignments
          </CardDescription>
        </CardHeader>
        <CardContent>
          <UserManagement />
        </CardContent>
      </Card>
      </div>
    </>
  );
}