import { useRef, useEffect, useCallback, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { FileText, Flag, AlertCircle, Activity, ShieldAlert } from 'lucide-react';
import { useUserRole } from '@/hooks/useUserRole';
import { useAuth } from '@/hooks/useAuth';
import { useRequireMFA } from '@/hooks/useRequireMFA';
import { MFAGuard } from '@/components/auth/MFAGuard';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { ModerationQueue, ModerationQueueRef } from '@/components/moderation/ModerationQueue';
import { ReportsQueue } from '@/components/moderation/ReportsQueue';
import { RecentActivity } from '@/components/moderation/RecentActivity';
import { useModerationStats } from '@/hooks/useModerationStats';
import { useAdminSettings } from '@/hooks/useAdminSettings';
import { supabase } from '@/lib/supabaseClient';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { QueueSkeleton } from '@/components/moderation/QueueSkeleton';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';

export default function AdminDashboard() {
  useDocumentTitle('Dashboard - Admin');
  const { user, loading: authLoading } = useAuth();
  const { isModerator, loading: roleLoading } = useUserRole();
  const { needsEnrollment, loading: mfaLoading } = useRequireMFA();
  const navigate = useNavigate();
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [activeTab, setActiveTab] = useState('moderation');
  const [suspiciousVersionsCount, setSuspiciousVersionsCount] = useState<number>(0);
  
  const moderationQueueRef = useRef<ModerationQueueRef>(null);
  const reportsQueueRef = useRef<any>(null);
  const recentActivityRef = useRef<any>(null);
  
  const { 
    getAdminPanelRefreshMode, 
    getAdminPanelPollInterval,
  } = useAdminSettings();
  
  const refreshMode = getAdminPanelRefreshMode();
  const pollInterval = getAdminPanelPollInterval();
  
  const { stats, refresh: refreshStats, optimisticallyUpdateStats, lastUpdated } = useModerationStats({
    enabled: !!user && !authLoading && !roleLoading && isModerator(),
    pollingEnabled: refreshMode === 'auto',
    pollingInterval: pollInterval,
  });

  // Check for suspicious versions (bypassed submission flow)
  const checkSuspiciousVersions = useCallback(async () => {
    if (!user || !isModerator()) return;
    
    // Query all version tables for suspicious entries (no changed_by)
    const queries = [
      supabase.from('park_versions').select('*', { count: 'exact', head: true }).is('created_by', null),
      supabase.from('ride_versions').select('*', { count: 'exact', head: true }).is('created_by', null),
      supabase.from('company_versions').select('*', { count: 'exact', head: true }).is('created_by', null),
      supabase.from('ride_model_versions').select('*', { count: 'exact', head: true }).is('created_by', null),
    ];
    
    const results = await Promise.all(queries);
    const totalCount = results.reduce((sum, result) => sum + (result.count || 0), 0);
    
    setSuspiciousVersionsCount(totalCount);
  }, [user, isModerator]);

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

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    await refreshStats();
    await checkSuspiciousVersions();
    
    // Refresh active tab's content
    switch (activeTab) {
      case 'moderation':
        moderationQueueRef.current?.refresh();
        break;
      case 'reports':
        reportsQueueRef.current?.refresh();
        break;
      case 'activity':
        recentActivityRef.current?.refresh();
        break;
    }
    
    setTimeout(() => setIsRefreshing(false), 500);
  }, [refreshStats, checkSuspiciousVersions, activeTab]);

  const handleStatCardClick = (cardType: 'submissions' | 'reports' | 'flagged') => {
    switch (cardType) {
      case 'submissions':
        setActiveTab('moderation');
        break;
      case 'reports':
        setActiveTab('reports');
        break;
      case 'flagged':
        setActiveTab('moderation');
        break;
    }
  };

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

  if (authLoading || roleLoading || mfaLoading) {
    return (
      <AdminLayout>
        <div className="space-y-6">
          <div>
            <h1 className="text-2xl font-bold tracking-tight">Admin Dashboard</h1>
            <p className="text-muted-foreground mt-1">Central hub for all moderation activity</p>
          </div>

          {/* Skeleton for stat cards */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {[1, 2, 3].map((i) => (
              <Card key={i}>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <Skeleton className="h-11 w-11 rounded-lg" />
                      <Skeleton className="h-4 w-32" />
                    </div>
                    <Skeleton className="h-10 w-16" />
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* Skeleton for tabs */}
          <div className="space-y-4">
            <Skeleton className="h-12 w-full" />
            <QueueSkeleton count={3} />
          </div>
        </div>
      </AdminLayout>
    );
  }

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

  const statCards = [
    {
      label: 'Pending Submissions',
      value: stats.pendingSubmissions,
      icon: FileText,
      color: 'amber',
      type: 'submissions' as const,
    },
    {
      label: 'Open Reports',
      value: stats.openReports,
      icon: Flag,
      color: 'red',
      type: 'reports' as const,
    },
    {
      label: 'Flagged Content',
      value: stats.flaggedContent,
      icon: AlertCircle,
      color: 'orange',
      type: 'flagged' as const,
    },
  ];

  return (
    <AdminLayout
      onRefresh={handleRefresh}
      refreshMode={refreshMode}
      pollInterval={pollInterval}
      lastUpdated={lastUpdated ?? undefined}
      isRefreshing={isRefreshing}
    >
      <MFAGuard>
        <div className="space-y-6">
          <div>
            <h1 className="text-2xl font-bold tracking-tight">Admin Dashboard</h1>
            <p className="text-muted-foreground mt-1">
              Central hub for all moderation activity
            </p>
          </div>

          {/* Security Warning for Suspicious Versions */}
          {suspiciousVersionsCount > 0 && (
            <Alert variant="destructive" className="border-red-500/50 bg-red-500/10">
              <ShieldAlert className="h-5 w-5" />
              <AlertDescription className="ml-2">
                <strong>Security Alert:</strong> {suspiciousVersionsCount} entity version{suspiciousVersionsCount !== 1 ? 's' : ''} detected without user attribution. 
                This may indicate submission flow bypass. Check admin audit logs for details.
              </AlertDescription>
            </Alert>
          )}

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {statCards.map((card) => {
              const Icon = card.icon;
              const colorClasses = {
                amber: {
                  card: 'hover:border-amber-500/50',
                  bg: 'bg-amber-500/10',
                  icon: 'text-amber-600 dark:text-amber-400',
                },
                red: {
                  card: 'hover:border-red-500/50',
                  bg: 'bg-red-500/10',
                  icon: 'text-red-600 dark:text-red-400',
                },
                orange: {
                  card: 'hover:border-orange-500/50',
                  bg: 'bg-orange-500/10',
                  icon: 'text-orange-600 dark:text-orange-400',
                },
              };
              const colors = colorClasses[card.color as keyof typeof colorClasses];
              
              return (
                <Card
                  key={card.label}
                  className={`${colors.card} transition-colors cursor-pointer`}
                  onClick={() => handleStatCardClick(card.type)}
                >
                  <CardContent className="flex items-center justify-between p-6">
                    <div className="flex items-center gap-4">
                      <div className={`p-3 ${colors.bg} rounded-lg`}>
                        <Icon className={`w-5 h-5 ${colors.icon}`} />
                      </div>
                      <div>
                        <p className="text-sm font-medium text-muted-foreground">
                          {card.label}
                        </p>
                      </div>
                    </div>
                    <div className="text-4xl font-bold">{card.value}</div>
                  </CardContent>
                </Card>
              );
            })}
          </div>

          <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
            <TabsList className="grid w-full grid-cols-3 h-auto p-1">
              <TabsTrigger value="moderation" className="flex items-center gap-2 py-3">
                <FileText className="w-4 h-4" />
                <span className="hidden sm:inline">Moderation Queue</span>
                <span className="sm:hidden">Queue</span>
                {stats.pendingSubmissions > 0 && (
                  <Badge variant="secondary" className="ml-1 bg-amber-500/20 text-amber-700 dark:text-amber-300">
                    {stats.pendingSubmissions}
                  </Badge>
                )}
              </TabsTrigger>
              <TabsTrigger value="reports" className="flex items-center gap-2 py-3">
                <Flag className="w-4 h-4" />
                <span className="hidden sm:inline">Reports</span>
                <span className="sm:hidden">Reports</span>
                {stats.openReports > 0 && (
                  <Badge variant="secondary" className="ml-1 bg-red-500/20 text-red-700 dark:text-red-300">
                    {stats.openReports}
                  </Badge>
                )}
              </TabsTrigger>
              <TabsTrigger value="activity" className="flex items-center gap-2 py-3">
                <Activity className="w-4 h-4" />
                <span className="hidden sm:inline">Recent Activity</span>
                <span className="sm:hidden">Activity</span>
              </TabsTrigger>
            </TabsList>

            <TabsContent value="moderation" className="mt-6" forceMount={true} hidden={activeTab !== 'moderation'}>
              <ModerationQueue ref={moderationQueueRef} optimisticallyUpdateStats={optimisticallyUpdateStats} />
            </TabsContent>

            <TabsContent value="reports" className="mt-6" forceMount={true} hidden={activeTab !== 'reports'}>
              <ReportsQueue ref={reportsQueueRef} />
            </TabsContent>

            <TabsContent value="activity" className="mt-6" forceMount={true} hidden={activeTab !== 'activity'}>
              <RecentActivity ref={recentActivityRef} />
            </TabsContent>
          </Tabs>
        </div>
      </MFAGuard>
    </AdminLayout>
  );
}
