'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import {
  Shield,
  FileText,
  Users,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Ban,
  Unlock,
  ChevronLeft,
  ChevronRight,
  ShieldCheck,
  ShieldAlert,
  ShieldX,
  Clock,
  CreditCard,
  Eye,
  Search,
  Activity,
  TrendingUp,
  UserCheck,
  UserX,
  BarChart3,
} from 'lucide-react';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from '@/components/ui/tabs';
import {
  Table,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useAppStore } from '@/store/app-store';
import type { ScamReportType, UserType } from '@/types';
import { toast } from 'sonner';

// ─── Helpers ────────────────────────────────────────────────────────────────

function formatBDT(amount: number): string {
  if (amount >= 10000000) return `৳${(amount / 10000000).toFixed(1)}Cr`;
  if (amount >= 100000) return `৳${(amount / 100000).toFixed(1)}L`;
  if (amount >= 1000) return `৳${(amount / 1000).toFixed(1)}K`;
  return `৳${amount.toLocaleString('en-BD')}`;
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-GB', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  });
}

function timeAgo(dateStr: string): string {
  const now = new Date();
  const date = new Date(dateStr);
  const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);
  if (seconds < 60) return 'Just now';
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 30) return `${days}d ago`;
  return `${Math.floor(days / 30)}mo ago`;
}

const riskConfig: Record<
  string,
  { label: string; color: string; bg: string; border: string; icon: React.ElementType; rowBg: string }
> = {
  low: {
    label: 'Low',
    color: 'text-emerald-600 dark:text-emerald-400',
    bg: 'bg-emerald-500/10',
    border: 'border-emerald-500/30',
    icon: ShieldCheck,
    rowBg: 'bg-emerald-500/[0.02] dark:bg-emerald-500/[0.04]',
  },
  medium: {
    label: 'Medium',
    color: 'text-yellow-600 dark:text-yellow-400',
    bg: 'bg-yellow-500/10',
    border: 'border-yellow-500/30',
    icon: ShieldAlert,
    rowBg: 'bg-yellow-500/[0.02] dark:bg-yellow-500/[0.04]',
  },
  high: {
    label: 'High',
    color: 'text-orange-600 dark:text-orange-400',
    bg: 'bg-orange-500/10',
    border: 'border-orange-500/30',
    icon: ShieldX,
    rowBg: 'bg-orange-500/[0.04] dark:bg-orange-500/[0.06]',
  },
  critical: {
    label: 'Critical',
    color: 'text-red-600 dark:text-red-400',
    bg: 'bg-red-500/10',
    border: 'border-red-500/30',
    icon: AlertTriangle,
    rowBg: 'bg-red-500/[0.04] dark:bg-red-500/[0.06]',
  },
};

const statusConfig: Record<string, { label: string; color: string; bg: string }> = {
  pending: {
    label: 'Pending',
    color: 'text-yellow-700 dark:text-yellow-300',
    bg: 'bg-yellow-500/15',
  },
  verified: {
    label: 'Verified',
    color: 'text-emerald-700 dark:text-emerald-300',
    bg: 'bg-emerald-500/15',
  },
  suspicious: {
    label: 'Suspicious',
    color: 'text-orange-700 dark:text-orange-300',
    bg: 'bg-orange-500/15',
  },
  rejected: {
    label: 'Rejected',
    color: 'text-red-700 dark:text-red-300',
    bg: 'bg-red-500/15',
  },
};

// ─── Admin Stats ────────────────────────────────────────────────────────────

interface AdminStats {
  totalReports: number;
  pendingReports: number;
  verifiedReports: number;
  totalUsers: number;
  activeUsers: number;
  bannedUsers: number;
}

// ─── Admin Log Entry ────────────────────────────────────────────────────────

interface AdminLogEntry {
  id: string;
  action: string;
  targetType: string | null;
  targetId: string | null;
  details: string | null;
  createdAt: string;
  admin?: { name: string | null; email: string } | null;
}

// ─── Admin Report Action Dialog ─────────────────────────────────────────────

function ReportActionDialog({
  open,
  onOpenChange,
  report,
  action,
  onConfirm,
  isSubmitting,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  report: ScamReportType | null;
  action: 'verified' | 'rejected' | 'suspicious' | null;
  onConfirm: (reportId: string, status: string) => void;
  isSubmitting: boolean;
}) {
  if (!report || !action) return null;

  const actionConfig: Record<string, { title: string; description: string; icon: React.ElementType; color: string }> = {
    verified: {
      title: 'Approve Report',
      description: `Are you sure you want to approve "${report.title}"? This will mark the report as verified.`,
      icon: CheckCircle2,
      color: 'text-emerald-500',
    },
    rejected: {
      title: 'Reject Report',
      description: `Are you sure you want to reject "${report.title}"? This will mark the report as rejected.`,
      icon: XCircle,
      color: 'text-red-500',
    },
    suspicious: {
      title: 'Mark as Suspicious',
      description: `Are you sure you want to mark "${report.title}" as suspicious?`,
      icon: AlertTriangle,
      color: 'text-orange-500',
    },
  };

  const config = actionConfig[action];
  const Icon = config.icon;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Icon className={`h-5 w-5 ${config.color}`} />
            {config.title}
          </DialogTitle>
          <DialogDescription>{config.description}</DialogDescription>
        </DialogHeader>
        <div className="py-2">
          <div className="rounded-lg bg-muted/50 p-3 text-sm space-y-1">
            <p><span className="font-medium">Title:</span> {report.title}</p>
            <p><span className="font-medium">Reporter:</span> {report.reporter?.name || report.reporter?.email || 'Unknown'}</p>
            <p><span className="font-medium">Risk Level:</span> {report.riskLevel}</p>
            {report.amountLost > 0 && (
              <p><span className="font-medium">Amount Lost:</span> {formatBDT(report.amountLost)}</p>
            )}
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
            Cancel
          </Button>
          <Button
            onClick={() => onConfirm(report.id, action)}
            disabled={isSubmitting}
            className={
              action === 'verified'
                ? 'bg-emerald-600 hover:bg-emerald-700'
                : action === 'rejected'
                  ? 'bg-red-600 hover:bg-red-700'
                  : 'bg-orange-600 hover:bg-orange-700'
            }
          >
            {isSubmitting ? 'Processing...' : 'Confirm'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ─── Ban User Dialog ────────────────────────────────────────────────────────

function BanUserDialog({
  open,
  onOpenChange,
  targetUser,
  onConfirm,
  isSubmitting,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  targetUser: UserType | null;
  onConfirm: (userId: string, banned: boolean, reason: string) => void;
  isSubmitting: boolean;
}) {
  const [reason, setReason] = useState('');

  if (!targetUser) return null;

  const isBanning = !targetUser.banned;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            {isBanning ? (
              <Ban className="h-5 w-5 text-red-500" />
            ) : (
              <Unlock className="h-5 w-5 text-emerald-500" />
            )}
            {isBanning ? 'Ban User' : 'Unban User'}
          </DialogTitle>
          <DialogDescription>
            {isBanning
              ? `Are you sure you want to ban ${targetUser.name || targetUser.email}? They will not be able to access their account.`
              : `Are you sure you want to unban ${targetUser.name || targetUser.email}? They will regain access to their account.`}
          </DialogDescription>
        </DialogHeader>
        {isBanning && (
          <div className="space-y-2">
            <Label htmlFor="ban-reason">Ban Reason</Label>
            <Textarea
              id="ban-reason"
              placeholder="Enter reason for banning this user..."
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              rows={3}
            />
          </div>
        )}
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
            Cancel
          </Button>
          <Button
            onClick={() => onConfirm(targetUser.id, isBanning, reason)}
            disabled={isSubmitting || (isBanning && !reason.trim())}
            className={isBanning ? 'bg-red-600 hover:bg-red-700' : 'bg-emerald-600 hover:bg-emerald-700'}
          >
            {isSubmitting ? 'Processing...' : isBanning ? 'Ban User' : 'Unban User'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ─── Recent Actions Log ─────────────────────────────────────────────────────

function RecentActionsLog({ reports, users }: { reports: ScamReportType[]; users: (UserType & { reportCount?: number })[] }) {
  const actions = (() => {
    const items: { id: string; label: string; time: string; icon: React.ElementType; iconColor: string; iconBg: string }[] = [];

    for (const report of reports.slice(0, 5)) {
      if (report.status === 'verified') {
        items.push({
          id: `approve-${report.id}`,
          label: `Approved "${report.title}"`,
          time: report.updatedAt,
          icon: CheckCircle2,
          iconColor: 'text-emerald-500',
          iconBg: 'bg-emerald-500/10',
        });
      } else if (report.status === 'rejected') {
        items.push({
          id: `reject-${report.id}`,
          label: `Rejected "${report.title}"`,
          time: report.updatedAt,
          icon: XCircle,
          iconColor: 'text-red-500',
          iconBg: 'bg-red-500/10',
        });
      } else if (report.status === 'suspicious') {
        items.push({
          id: `suspicious-${report.id}`,
          label: `Marked "${report.title}" as suspicious`,
          time: report.updatedAt,
          icon: AlertTriangle,
          iconColor: 'text-orange-500',
          iconBg: 'bg-orange-500/10',
        });
      }

      items.push({
        id: `new-${report.id}`,
        label: `New report: "${report.title}"`,
        time: report.createdAt,
        icon: FileText,
        iconColor: 'text-blue-500',
        iconBg: 'bg-blue-500/10',
      });
    }

    for (const u of users.slice(0, 3)) {
      if (u.banned) {
        items.push({
          id: `ban-${u.id}`,
          label: `Banned user ${u.name || u.email}`,
          time: '',
          icon: Ban,
          iconColor: 'text-red-500',
          iconBg: 'bg-red-500/10',
        });
      }
    }

    items.sort((a, b) => {
      if (!a.time) return 1;
      if (!b.time) return -1;
      return new Date(b.time).getTime() - new Date(a.time).getTime();
    });

    return items.slice(0, 6);
  })();

  if (actions.length === 0) {
    return (
      <div className="text-center py-6">
        <Activity className="h-8 w-8 text-muted-foreground/30 mx-auto mb-2" />
        <p className="text-xs text-muted-foreground">No recent actions</p>
      </div>
    );
  }

  return (
    <div className="space-y-0 max-h-64 overflow-y-auto custom-scrollbar">
      {actions.map((action, idx) => {
        const Icon = action.icon;
        return (
          <div key={action.id} className="flex gap-3 py-2">
            <div className={`p-1.5 rounded-lg ${action.iconBg} shrink-0`}>
              <Icon className={`h-3.5 w-3.5 ${action.iconColor}`} />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-xs line-clamp-1">{action.label}</p>
              {action.time && (
                <p className="text-[10px] text-muted-foreground flex items-center gap-1">
                  <Clock className="h-2.5 w-2.5" />
                  {timeAgo(action.time)}
                </p>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Main Component ─────────────────────────────────────────────────────────

export function AdminPage() {
  const user = useAppStore((s) => s.user);
  const navigate = useAppStore((s) => s.navigate);

  const [activeTab, setActiveTab] = useState('reports');
  const [reports, setReports] = useState<ScamReportType[]>([]);
  const [users, setUsers] = useState<(UserType & { reportCount?: number })[]>([]);
  const [isLoadingReports, setIsLoadingReports] = useState(true);
  const [isLoadingUsers, setIsLoadingUsers] = useState(true);
  const [isLoadingStats, setIsLoadingStats] = useState(true);
  const [reportPage, setReportPage] = useState(1);
  const [userPage, setUserPage] = useState(1);
  const [totalReportPages, setTotalReportPages] = useState(1);
  const [totalUserPages, setTotalUserPages] = useState(1);
  const [adminStats, setAdminStats] = useState<AdminStats>({
    totalReports: 0,
    pendingReports: 0,
    verifiedReports: 0,
    totalUsers: 0,
    activeUsers: 0,
    bannedUsers: 0,
  });

  // Search and filter
  const [reportSearch, setReportSearch] = useState('');
  const [reportStatusFilter, setReportStatusFilter] = useState('all');

  // Dialog state
  const [actionDialogOpen, setActionDialogOpen] = useState(false);
  const [selectedReport, setSelectedReport] = useState<ScamReportType | null>(null);
  const [selectedAction, setSelectedAction] = useState<'verified' | 'rejected' | 'suspicious' | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const [banDialogOpen, setBanDialogOpen] = useState(false);
  const [targetUser, setTargetUser] = useState<UserType | null>(null);
  const [isSubmittingBan, setIsSubmittingBan] = useState(false);

  // Access check
  useEffect(() => {
    if (user && user.role !== 'admin') {
      navigate('home');
    }
  }, [user, navigate]);

  // Fetch admin stats
  useEffect(() => {
    if (user?.role !== 'admin') return;

    const fetchStats = async () => {
      setIsLoadingStats(true);
      try {
        const [analyticsRes, usersRes] = await Promise.all([
          fetch('/api/analytics'),
          fetch('/api/admin/users?page=1&limit=100'),
        ]);

        const analyticsData = await analyticsRes.json();
        const usersData = await usersRes.json();

        let totalUsers = 0;
        let activeUsers = 0;
        let bannedUsers = 0;
        let pendingReports = 0;

        if (usersData.success) {
          const allUsers = usersData.data.users || [];
          totalUsers = usersData.data.pagination?.total || allUsers.length;
          bannedUsers = allUsers.filter((u: UserType) => u.banned).length;
          activeUsers = totalUsers - bannedUsers;
        }

        // Count pending from reports fetch
        try {
          const pendingRes = await fetch('/api/admin/reports?status=pending&limit=1');
          const pendingData = await pendingRes.json();
          if (pendingData.success) {
            pendingReports = pendingData.data.pagination?.total || 0;
          }
        } catch {
          // Ignore
        }

        if (analyticsData.success) {
          setAdminStats({
            totalReports: analyticsData.data.totalReports || 0,
            pendingReports,
            verifiedReports: analyticsData.data.verifiedReports || 0,
            totalUsers,
            activeUsers,
            bannedUsers,
          });
        }
      } catch {
        toast.error('Failed to load admin statistics');
      } finally {
        setIsLoadingStats(false);
      }
    };

    fetchStats();
  }, [user]);

  // Debounced search
  const [debouncedSearch, setDebouncedSearch] = useState('');

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(reportSearch), 400);
    return () => clearTimeout(timer);
  }, [reportSearch]);

  // Fetch reports
  const fetchReports = useCallback(async () => {
    setIsLoadingReports(true);
    try {
      const params = new URLSearchParams({
        page: reportPage.toString(),
        limit: '10',
      });
      if (reportStatusFilter !== 'all') {
        params.set('status', reportStatusFilter);
      }
      if (debouncedSearch.trim()) {
        params.set('search', debouncedSearch.trim());
      }

      const res = await fetch(`/api/admin/reports?${params}`);
      if (!res.ok) throw new Error('Network error');
      const data = await res.json();
      if (data.success) {
        setReports(data.data.reports || []);
        setTotalReportPages(data.data.pagination?.totalPages || 1);
      } else {
        toast.error(data.error || 'Failed to load reports');
      }
    } catch {
      toast.error('Failed to load reports. Please try again.');
    } finally {
      setIsLoadingReports(false);
    }
  }, [reportPage, debouncedSearch, reportStatusFilter]);

  // Fetch users
  const fetchUsers = useCallback(async () => {
    setIsLoadingUsers(true);
    try {
      const res = await fetch(`/api/admin/users?page=${userPage}&limit=10`);
      if (!res.ok) throw new Error('Network error');
      const data = await res.json();
      if (data.success) {
        setUsers(data.data.users || []);
        setTotalUserPages(data.data.pagination?.totalPages || 1);
      } else {
        toast.error(data.error || 'Failed to load users');
      }
    } catch {
      toast.error('Failed to load users. Please try again.');
    } finally {
      setIsLoadingUsers(false);
    }
  }, [userPage]);

  useEffect(() => {
    if (user?.role === 'admin') fetchReports();
  }, [fetchReports, user]);

  useEffect(() => {
    if (user?.role === 'admin' && activeTab === 'users') fetchUsers();
  }, [fetchUsers, activeTab, user]);

  // Reset page when search/filter changes
  useEffect(() => {
    setReportPage(1);
  }, [debouncedSearch, reportStatusFilter]);

  const handleReportAction = async (reportId: string, status: string) => {
    setIsSubmitting(true);
    try {
      const res = await fetch(`/api/admin/reports/${reportId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status, adminId: user?.id }),
      });
      if (!res.ok) throw new Error('Network error');
      const data = await res.json();
      if (data.success) {
        toast.success(`Report ${status === 'verified' ? 'approved' : status === 'rejected' ? 'rejected' : 'marked as suspicious'}`);
        fetchReports();
        // Refresh stats
        setAdminStats((prev) => ({
          ...prev,
          pendingReports: Math.max(0, prev.pendingReports - 1),
          verifiedReports: status === 'verified' ? prev.verifiedReports + 1 : prev.verifiedReports,
        }));
      } else {
        toast.error(data.error || 'Failed to update report');
      }
    } catch {
      toast.error('Failed to update report. Please try again.');
    } finally {
      setIsSubmitting(false);
      setActionDialogOpen(false);
      setSelectedReport(null);
      setSelectedAction(null);
    }
  };

  const handleBanUser = async (userId: string, banned: boolean, reason: string) => {
    setIsSubmittingBan(true);
    try {
      const res = await fetch(`/api/admin/users/${userId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ banned, banReason: reason, adminId: user?.id }),
      });
      if (!res.ok) throw new Error('Network error');
      const data = await res.json();
      if (data.success) {
        toast.success(banned ? 'User banned successfully' : 'User unbanned successfully');
        fetchUsers();
        setAdminStats((prev) => ({
          ...prev,
          bannedUsers: banned ? prev.bannedUsers + 1 : Math.max(0, prev.bannedUsers - 1),
          activeUsers: banned ? Math.max(0, prev.activeUsers - 1) : prev.activeUsers + 1,
        }));
      } else {
        toast.error(data.error || 'Failed to update user');
      }
    } catch {
      toast.error('Failed to update user. Please try again.');
    } finally {
      setIsSubmittingBan(false);
      setBanDialogOpen(false);
      setTargetUser(null);
    }
  };

  const openActionDialog = (report: ScamReportType, action: 'verified' | 'rejected' | 'suspicious') => {
    setSelectedReport(report);
    setSelectedAction(action);
    setActionDialogOpen(true);
  };

  if (!user || user.role !== 'admin') {
    return (
      <div className="max-w-4xl mx-auto px-4 py-16 text-center">
        <Card className="border-red-500/30 bg-red-500/5">
          <CardContent className="py-16">
            <Shield className="h-16 w-16 text-red-500 mx-auto mb-4" />
            <h2 className="text-2xl font-bold mb-2">Access Denied</h2>
            <p className="text-muted-foreground mb-6">
              You don&apos;t have permission to access the admin panel.
            </p>
            <Button onClick={() => navigate('home')} variant="outline">
              Back to Home
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  const statsCards = [
    {
      icon: FileText,
      label: 'Total Reports',
      value: adminStats.totalReports,
      color: 'text-emerald-500',
      bgIcon: 'bg-emerald-500/10',
    },
    {
      icon: Clock,
      label: 'Pending',
      value: adminStats.pendingReports,
      color: 'text-yellow-500',
      bgIcon: 'bg-yellow-500/10',
    },
    {
      icon: CheckCircle2,
      label: 'Verified',
      value: adminStats.verifiedReports,
      color: 'text-teal-500',
      bgIcon: 'bg-teal-500/10',
    },
    {
      icon: Users,
      label: 'Total Users',
      value: adminStats.totalUsers,
      color: 'text-blue-500',
      bgIcon: 'bg-blue-500/10',
    },
    {
      icon: UserCheck,
      label: 'Active Users',
      value: adminStats.activeUsers,
      color: 'text-cyan-500',
      bgIcon: 'bg-cyan-500/10',
    },
    {
      icon: UserX,
      label: 'Banned Users',
      value: adminStats.bannedUsers,
      color: 'text-red-500',
      bgIcon: 'bg-red-500/10',
    },
  ];

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
      <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.4 }}>
        {/* ─── Header ──────────────────────────────────────────────────────── */}
        <div className="flex items-center gap-3 mb-8">
          <div className="p-2.5 rounded-xl bg-emerald-500/10">
            <Shield className="h-6 w-6 text-emerald-500" />
          </div>
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold">Admin Panel</h1>
            <p className="text-muted-foreground text-sm sm:text-base">
              Manage reports, users, and platform data
            </p>
          </div>
        </div>

        {/* ─── Stats Summary Cards ─────────────────────────────────────────── */}
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 mb-8">
          {statsCards.map((stat, idx) => (
            <motion.div
              key={stat.label}
              initial={{ opacity: 0, y: 15 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: idx * 0.05, duration: 0.3 }}
            >
              <Card className="glass border-0 shadow-lg hover:shadow-xl hover:shadow-emerald-500/5 transition-all duration-300 group">
                <CardContent className="p-3 sm:p-4">
                  <div className={`${stat.bgIcon} p-2 rounded-lg w-fit mb-2 group-hover:scale-110 transition-transform duration-300`}>
                    <stat.icon className={`h-4 w-4 ${stat.color}`} />
                  </div>
                  <div className="text-lg sm:text-xl font-bold">
                    {isLoadingStats ? (
                      <Skeleton className="h-6 w-10" />
                    ) : (
                      stat.value
                    )}
                  </div>
                  <p className="text-xs text-muted-foreground">{stat.label}</p>
                </CardContent>
              </Card>
            </motion.div>
          ))}
        </div>

        {/* ─── Tabs ────────────────────────────────────────────────────────── */}
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="mb-6">
            <TabsTrigger value="reports" className="gap-2">
              <FileText className="h-4 w-4" />
              Reports
            </TabsTrigger>
            <TabsTrigger value="users" className="gap-2">
              <Users className="h-4 w-4" />
              Users
            </TabsTrigger>
          </TabsList>

          {/* ─── Reports Tab ──────────────────────────────────────────────── */}
          <TabsContent value="reports">
            <Card className="glass border-0 shadow-lg">
              <CardHeader>
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                  <div>
                    <CardTitle>Report Management</CardTitle>
                    <CardDescription>Review and moderate reported scams</CardDescription>
                  </div>
                </div>
                {/* Search and Filter Bar */}
                <div className="flex flex-col sm:flex-row gap-2 mt-3">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="Search reports by title, description, phone..."
                      value={reportSearch}
                      onChange={(e) => setReportSearch(e.target.value)}
                      className="pl-9 h-9"
                    />
                  </div>
                  <Select value={reportStatusFilter} onValueChange={setReportStatusFilter}>
                    <SelectTrigger className="w-[150px] h-9">
                      <SelectValue placeholder="Filter status" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Status</SelectItem>
                      <SelectItem value="pending">Pending</SelectItem>
                      <SelectItem value="verified">Verified</SelectItem>
                      <SelectItem value="suspicious">Suspicious</SelectItem>
                      <SelectItem value="rejected">Rejected</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardHeader>
              <CardContent>
                {isLoadingReports ? (
                  <div className="space-y-3">
                    {[1, 2, 3, 4].map((i) => (
                      <div key={i} className="flex items-center gap-4">
                        <Skeleton className="h-4 w-8" />
                        <Skeleton className="h-4 flex-1" />
                        <Skeleton className="h-4 w-20" />
                        <Skeleton className="h-4 w-16" />
                        <Skeleton className="h-8 w-24" />
                      </div>
                    ))}
                  </div>
                ) : reports.length === 0 ? (
                  <div className="py-12 text-center">
                    <FileText className="h-12 w-12 text-muted-foreground/40 mx-auto mb-3" />
                    <p className="text-muted-foreground">
                      {reportSearch || reportStatusFilter !== 'all'
                        ? 'No reports match your search criteria'
                        : 'No reports to review'}
                    </p>
                    {(reportSearch || reportStatusFilter !== 'all') && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          setReportSearch('');
                          setReportStatusFilter('all');
                        }}
                        className="mt-3"
                      >
                        Clear Filters
                      </Button>
                    )}
                  </div>
                ) : (
                  <>
                    {/* Desktop Table */}
                    <div className="hidden md:block overflow-x-auto">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-[250px]">Title</TableHead>
                            <TableHead>Reporter</TableHead>
                            <TableHead>Category</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead>Risk</TableHead>
                            <TableHead>Date</TableHead>
                            <TableHead className="text-right">Actions</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {reports.map((report) => {
                            const risk = riskConfig[report.riskLevel] || riskConfig.low;
                            const RiskIcon = risk.icon;
                            const status = statusConfig[report.status] || statusConfig.pending;
                            return (
                              <TableRow
                                key={report.id}
                                className={`${risk.rowBg} hover:${risk.rowBg} transition-colors`}
                              >
                                <TableCell className="font-medium max-w-[250px] truncate">
                                  <div className="flex items-center gap-2">
                                    {/* Risk color indicator dot */}
                                    <div className={`w-1.5 h-5 rounded-full shrink-0 ${
                                      report.riskLevel === 'critical' ? 'bg-red-500' :
                                      report.riskLevel === 'high' ? 'bg-orange-500' :
                                      report.riskLevel === 'medium' ? 'bg-yellow-500' :
                                      'bg-emerald-500'
                                    }`} />
                                    <span className="truncate">{report.title}</span>
                                  </div>
                                </TableCell>
                                <TableCell className="text-sm">
                                  {report.reporter?.name || report.reporter?.email || 'Unknown'}
                                </TableCell>
                                <TableCell>
                                  <Badge variant="secondary" className="text-xs">
                                    {report.category?.name || report.scamType}
                                  </Badge>
                                </TableCell>
                                <TableCell>
                                  <Badge variant="secondary" className={`text-xs ${status.color} ${status.bg}`}>
                                    {status.label}
                                  </Badge>
                                </TableCell>
                                <TableCell>
                                  <Badge variant="outline" className={`text-xs ${risk.color} ${risk.border} ${risk.bg}`}>
                                    <RiskIcon className="h-3 w-3" />
                                    {risk.label}
                                  </Badge>
                                </TableCell>
                                <TableCell className="text-sm text-muted-foreground">
                                  {formatDate(report.createdAt)}
                                </TableCell>
                                <TableCell className="text-right">
                                  <div className="flex items-center justify-end gap-1">
                                    {report.status === 'pending' && (
                                      <>
                                        <Button
                                          size="sm"
                                          variant="ghost"
                                          onClick={() => openActionDialog(report, 'verified')}
                                          className="h-8 text-emerald-600 hover:text-emerald-700 hover:bg-emerald-500/10"
                                        >
                                          <CheckCircle2 className="h-4 w-4" />
                                        </Button>
                                        <Button
                                          size="sm"
                                          variant="ghost"
                                          onClick={() => openActionDialog(report, 'rejected')}
                                          className="h-8 text-red-600 hover:text-red-700 hover:bg-red-500/10"
                                        >
                                          <XCircle className="h-4 w-4" />
                                        </Button>
                                        <Button
                                          size="sm"
                                          variant="ghost"
                                          onClick={() => openActionDialog(report, 'suspicious')}
                                          className="h-8 text-orange-600 hover:text-orange-700 hover:bg-orange-500/10"
                                        >
                                          <AlertTriangle className="h-4 w-4" />
                                        </Button>
                                      </>
                                    )}
                                    {report.status !== 'pending' && (
                                      <span className="text-xs text-muted-foreground">Reviewed</span>
                                    )}
                                  </div>
                                </TableCell>
                              </TableRow>
                            );
                          })}
                        </TableBody>
                      </Table>
                    </div>

                    {/* Mobile Cards */}
                    <div className="md:hidden space-y-3">
                      {reports.map((report) => {
                        const risk = riskConfig[report.riskLevel] || riskConfig.low;
                        const RiskIcon = risk.icon;
                        const status = statusConfig[report.status] || statusConfig.pending;
                        return (
                          <Card key={report.id} className={`border border-border/50 ${risk.rowBg} card-themed`}>
                            <CardContent className="p-4">
                              <div className="flex items-start gap-2 mb-2">
                                <div className={`w-1 h-full min-h-[40px] rounded-full shrink-0 ${
                                  report.riskLevel === 'critical' ? 'bg-red-500' :
                                  report.riskLevel === 'high' ? 'bg-orange-500' :
                                  report.riskLevel === 'medium' ? 'bg-yellow-500' :
                                  'bg-emerald-500'
                                }`} />
                                <div className="flex-1 min-w-0">
                                  <h3 className="font-semibold line-clamp-1">{report.title}</h3>
                                  <div className="flex flex-wrap gap-1.5 mt-1.5">
                                    <Badge variant="secondary" className={`text-xs ${status.color} ${status.bg}`}>
                                      {status.label}
                                    </Badge>
                                    <Badge variant="outline" className={`text-xs ${risk.color} ${risk.border} ${risk.bg}`}>
                                      <RiskIcon className="h-3 w-3" />
                                      {risk.label}
                                    </Badge>
                                  </div>
                                </div>
                              </div>
                              <div className="text-xs text-muted-foreground space-y-1 mb-3 pl-3">
                                <p>Reporter: {report.reporter?.name || report.reporter?.email || 'Unknown'}</p>
                                <p>Category: {report.category?.name || report.scamType}</p>
                                <p>Date: {formatDate(report.createdAt)}</p>
                              </div>
                              {report.status === 'pending' && (
                                <div className="flex gap-2 pl-3">
                                  <Button
                                    size="sm"
                                    onClick={() => openActionDialog(report, 'verified')}
                                    className="h-8 text-xs bg-emerald-600 hover:bg-emerald-700"
                                  >
                                    <CheckCircle2 className="h-3 w-3" />
                                    Approve
                                  </Button>
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() => openActionDialog(report, 'suspicious')}
                                    className="h-8 text-xs border-orange-500/30 text-orange-600 hover:bg-orange-500/10"
                                  >
                                    <AlertTriangle className="h-3 w-3" />
                                    Suspicious
                                  </Button>
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() => openActionDialog(report, 'rejected')}
                                    className="h-8 text-xs border-red-500/30 text-red-600 hover:bg-red-500/10"
                                  >
                                    <XCircle className="h-3 w-3" />
                                    Reject
                                  </Button>
                                </div>
                              )}
                            </CardContent>
                          </Card>
                        );
                      })}
                    </div>

                    {/* Pagination */}
                    <div className="flex items-center justify-between mt-6 pt-4 border-t">
                      <p className="text-sm text-muted-foreground">
                        Page {reportPage} of {totalReportPages}
                      </p>
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => setReportPage((p) => Math.max(1, p - 1))}
                          disabled={reportPage <= 1}
                        >
                          <ChevronLeft className="h-4 w-4" />
                          Previous
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => setReportPage((p) => Math.min(totalReportPages, p + 1))}
                          disabled={reportPage >= totalReportPages}
                        >
                          Next
                          <ChevronRight className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  </>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* ─── Users Tab ────────────────────────────────────────────────── */}
          <TabsContent value="users">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              {/* Users Table */}
              <div className="lg:col-span-2">
                <Card className="glass border-0 shadow-lg">
                  <CardHeader>
                    <CardTitle>User Management</CardTitle>
                    <CardDescription>Manage user accounts and permissions</CardDescription>
                  </CardHeader>
                  <CardContent>
                    {isLoadingUsers ? (
                      <div className="space-y-3">
                        {[1, 2, 3, 4].map((i) => (
                          <div key={i} className="flex items-center gap-4">
                            <Skeleton className="h-4 w-8" />
                            <Skeleton className="h-4 flex-1" />
                            <Skeleton className="h-4 w-20" />
                            <Skeleton className="h-8 w-20" />
                          </div>
                        ))}
                      </div>
                    ) : users.length === 0 ? (
                      <div className="py-12 text-center">
                        <Users className="h-12 w-12 text-muted-foreground/40 mx-auto mb-3" />
                        <p className="text-muted-foreground">No users found</p>
                      </div>
                    ) : (
                      <>
                        {/* Desktop Table */}
                        <div className="hidden md:block overflow-x-auto">
                          <Table>
                            <TableHeader>
                              <TableRow>
                                <TableHead>Name</TableHead>
                                <TableHead>Email</TableHead>
                                <TableHead>Role</TableHead>
                                <TableHead>Reports</TableHead>
                                <TableHead>Status</TableHead>
                                <TableHead className="text-right">Actions</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {users.map((u) => (
                                <TableRow key={u.id} className={u.banned ? 'bg-red-500/[0.03] dark:bg-red-500/[0.05]' : ''}>
                                  <TableCell className="font-medium">
                                    {u.name || 'Unnamed'}
                                  </TableCell>
                                  <TableCell className="text-sm text-muted-foreground">
                                    {u.email}
                                  </TableCell>
                                  <TableCell>
                                    <Badge
                                      variant={u.role === 'admin' ? 'default' : 'secondary'}
                                      className="text-xs"
                                    >
                                      {u.role === 'admin' ? (
                                        <><Shield className="h-3 w-3" /> Admin</>
                                      ) : (
                                        'User'
                                      )}
                                    </Badge>
                                  </TableCell>
                                  <TableCell className="text-sm">
                                    {(u as UserType & { reportCount?: number }).reportCount ?? 0}
                                  </TableCell>
                                  <TableCell>
                                    <Badge
                                      variant="secondary"
                                      className={`text-xs ${
                                        u.banned
                                          ? 'text-red-700 dark:text-red-300 bg-red-500/15'
                                          : 'text-emerald-700 dark:text-emerald-300 bg-emerald-500/15'
                                      }`}
                                    >
                                      {u.banned ? 'Banned' : 'Active'}
                                    </Badge>
                                  </TableCell>
                                  <TableCell className="text-right">
                                    {u.role !== 'admin' && (
                                      <Button
                                        size="sm"
                                        variant={u.banned ? 'outline' : 'ghost'}
                                        onClick={() => {
                                          setTargetUser(u);
                                          setBanDialogOpen(true);
                                        }}
                                        className={
                                          u.banned
                                            ? 'h-8 text-emerald-600 hover:text-emerald-700 hover:bg-emerald-500/10 border-emerald-500/30'
                                            : 'h-8 text-red-600 hover:text-red-700 hover:bg-red-500/10'
                                        }
                                      >
                                        {u.banned ? (
                                          <><Unlock className="h-3 w-3" /> Unban</>
                                        ) : (
                                          <><Ban className="h-3 w-3" /> Ban</>
                                        )}
                                      </Button>
                                    )}
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>

                        {/* Mobile Cards */}
                        <div className="md:hidden space-y-3">
                          {users.map((u) => (
                            <Card key={u.id} className={`border border-border/50 ${u.banned ? 'bg-red-500/[0.03] dark:bg-red-500/[0.05]' : ''}`}>
                              <CardContent className="p-4">
                                <div className="flex items-start justify-between">
                                  <div>
                                    <h3 className="font-semibold">{u.name || 'Unnamed'}</h3>
                                    <p className="text-xs text-muted-foreground">{u.email}</p>
                                  </div>
                                  <Badge
                                    variant="secondary"
                                    className={`text-xs ${
                                      u.banned
                                        ? 'text-red-700 dark:text-red-300 bg-red-500/15'
                                        : 'text-emerald-700 dark:text-emerald-300 bg-emerald-500/15'
                                    }`}
                                  >
                                    {u.banned ? 'Banned' : 'Active'}
                                  </Badge>
                                </div>
                                <div className="flex items-center gap-2 mt-2">
                                  <Badge variant={u.role === 'admin' ? 'default' : 'secondary'} className="text-xs">
                                    {u.role === 'admin' ? 'Admin' : 'User'}
                                  </Badge>
                                  <span className="text-xs text-muted-foreground">
                                    {(u as UserType & { reportCount?: number }).reportCount ?? 0} reports
                                  </span>
                                </div>
                                {u.role !== 'admin' && (
                                  <Button
                                    size="sm"
                                    variant={u.banned ? 'outline' : 'ghost'}
                                    onClick={() => {
                                      setTargetUser(u);
                                      setBanDialogOpen(true);
                                    }}
                                    className={`mt-3 h-8 text-xs ${
                                      u.banned
                                        ? 'text-emerald-600 hover:bg-emerald-500/10 border-emerald-500/30'
                                        : 'text-red-600 hover:bg-red-500/10'
                                    }`}
                                  >
                                    {u.banned ? (
                                      <><Unlock className="h-3 w-3" /> Unban</>
                                    ) : (
                                      <><Ban className="h-3 w-3" /> Ban</>
                                    )}
                                  </Button>
                                )}
                              </CardContent>
                            </Card>
                          ))}
                        </div>

                        {/* Pagination */}
                        <div className="flex items-center justify-between mt-6 pt-4 border-t">
                          <p className="text-sm text-muted-foreground">
                            Page {userPage} of {totalUserPages}
                          </p>
                          <div className="flex gap-2">
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => setUserPage((p) => Math.max(1, p - 1))}
                              disabled={userPage <= 1}
                            >
                              <ChevronLeft className="h-4 w-4" />
                              Previous
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => setUserPage((p) => Math.min(totalUserPages, p + 1))}
                              disabled={userPage >= totalUserPages}
                            >
                              Next
                              <ChevronRight className="h-4 w-4" />
                            </Button>
                          </div>
                        </div>
                      </>
                    )}
                  </CardContent>
                </Card>
              </div>

              {/* Sidebar - Recent Actions */}
              <div>
                <Card className="glass border-0 shadow-lg">
                  <CardHeader className="pb-3">
                    <CardTitle className="text-base flex items-center gap-2">
                      <Activity className="h-4 w-4 text-emerald-500" />
                      Recent Actions
                    </CardTitle>
                    <CardDescription className="text-xs">
                      Latest moderation activity
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <RecentActionsLog reports={reports} users={users} />
                  </CardContent>
                </Card>

                {/* Quick Stats */}
                <Card className="glass border-0 shadow-lg mt-6">
                  <CardHeader className="pb-3">
                    <CardTitle className="text-base flex items-center gap-2">
                      <BarChart3 className="h-4 w-4 text-teal-500" />
                      Report Distribution
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      {[
                        { label: 'Pending', count: adminStats.pendingReports, color: 'bg-yellow-500', bgLight: 'bg-yellow-500/10' },
                        { label: 'Verified', count: adminStats.verifiedReports, color: 'bg-emerald-500', bgLight: 'bg-emerald-500/10' },
                        { label: 'Total', count: adminStats.totalReports, color: 'bg-teal-500', bgLight: 'bg-teal-500/10' },
                      ].map((item) => {
                        const pct = adminStats.totalReports > 0
                          ? Math.round((item.count / adminStats.totalReports) * 100)
                          : 0;
                        return (
                          <div key={item.label}>
                            <div className="flex items-center justify-between text-xs mb-1">
                              <span className="text-muted-foreground">{item.label}</span>
                              <span className="font-medium">{item.count} ({pct}%)</span>
                            </div>
                            <div className={`h-2 rounded-full ${item.bgLight}`}>
                              <motion.div
                                initial={{ width: 0 }}
                                animate={{ width: `${pct}%` }}
                                transition={{ duration: 0.5, ease: 'easeOut' }}
                                className={`h-full rounded-full ${item.color}`}
                              />
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </motion.div>

      {/* ─── Dialogs ──────────────────────────────────────────────────────── */}
      <ReportActionDialog
        open={actionDialogOpen}
        onOpenChange={setActionDialogOpen}
        report={selectedReport}
        action={selectedAction}
        onConfirm={handleReportAction}
        isSubmitting={isSubmitting}
      />

      <BanUserDialog
        open={banDialogOpen}
        onOpenChange={setBanDialogOpen}
        targetUser={targetUser}
        onConfirm={handleBanUser}
        isSubmitting={isSubmittingBan}
      />
    </div>
  );
}
