'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import AdminMCQManager from '@/components/admin/AdminMCQManager';
import AdminPayments from '@/components/admin/AdminPayments';
import { AdminSettings as AdminCustomizer } from '@/components/admin/AdminSettings';
import { AdminTeams } from '@/components/admin/AdminTeams';
import { AdminRoles } from '@/components/admin/AdminRoles';
import { AdminNotifications } from '@/components/admin/AdminNotifications';
import { AdminMenus } from '@/components/admin/AdminMenus';
import { AdminServer } from '@/components/admin/AdminServer';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  LayoutDashboard,
  Users,
  Building2,
  Store,
  ShoppingBag,
  Package,
  GraduationCap,
  MessageSquare,
  Settings,
  LogOut,
  Shield,
  ArrowLeft,
  Mail,
  Lock,
  TrendingUp,
  TrendingDown,
  DollarSign,
  UserCheck,
  Clock,
  Bell,
  Plus,
  Search,
  Eye,
  Trash2,
  CheckCircle,
  XCircle,
  Ban,
  ChevronLeft,
  Activity,
  BarChart3,
  UsersRound,
  Crown,
  Menu as MenuIcon,
  Send,
  Palette,
  Server as ServerIcon,
  CreditCard,
} from 'lucide-react';

// Authenticated fetch helper for admin API calls
function adminFetch(url: string, options: RequestInit = {}): Promise<Response> {
  const token = typeof window !== 'undefined' ? useAppStore.getState().adminToken : null;
  const headers = new Headers(options.headers);
  if (token) {
    headers.set('x-admin-token', token);
  }
  if (!headers.has('Content-Type') && options.body) {
    headers.set('Content-Type', 'application/json');
  }
  return fetch(url, { ...options, headers }).then((res) => {
    if (res.status === 401) {
      useAppStore.getState().adminLogout();
    }
    return res;
  });
}

// ============ ADMIN LOGIN ============
function AdminLogin() {
  const { language, setAdminUser, setAdminTab } = useAppStore();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !password) return;

    setIsLoading(true);
    setError('');

    try {
      const res = await fetch('/api/admin/auth', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });

      const data = await res.json();

      if (data.success) {
        setAdminUser({
          id: data.admin.id,
          name: data.admin.name,
          email: data.admin.email,
          role: data.admin.role,
          permissions: data.admin.permissions,
        }, data.admin.token);
        setAdminTab('dashboard');
      } else {
        setError(data.error || 'Invalid credentials');
      }
    } catch {
      setError('Network error. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center px-4 py-8">
      <div className="w-full max-w-md">
        {/* Back Button */}
        <div className="mb-4">
          <button
            onClick={() => useAppStore.getState().setCurrentSection('home')}
            className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
          >
            <ArrowLeft className="h-4 w-4" />
            {language === 'en' ? 'Back to App' : 'অ্যাপে ফিরুন'}
          </button>
        </div>
        {/* Admin Header */}
        <div className="mb-6 rounded-t-2xl bg-gradient-to-br from-orange-600 via-orange-500 to-amber-500 px-6 py-10 text-center shadow-xl">
          <div className="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm">
            <Shield className="h-10 w-10 text-white" strokeWidth={1.5} />
          </div>
          <h1 className="text-2xl font-bold text-white">
            {t('admin.title', language)}
          </h1>
          <p className="mt-1 text-sm text-white/80">
            {t('admin.signIn', language)}
          </p>
        </div>

        <Card className="rounded-t-none border-t-0 shadow-xl">
          <CardContent className="pt-6">
            <form onSubmit={handleLogin} className="space-y-4">
              {error && (
                <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 text-center text-sm text-destructive">
                  {error}
                </div>
              )}

              <div className="space-y-2">
                <Label htmlFor="admin-email">
                  {t('admin.email', language)}
                </Label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="admin-email"
                    type="email"
                    placeholder="admin@needyfy.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="pl-9"
                    required
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="admin-password">
                  {t('admin.password', language)}
                </Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="admin-password"
                    type="password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="pl-9"
                    required
                  />
                </div>
              </div>

              <Button
                type="submit"
                className="w-full bg-gradient-to-r from-orange-600 to-amber-500 font-semibold shadow-md hover:from-orange-700 hover:to-amber-600"
                size="lg"
                disabled={isLoading}
              >
                {isLoading ? (
                  <span className="flex items-center gap-2">
                    <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                    {t('common.loading', language)}
                  </span>
                ) : (
                  <span className="flex items-center gap-2">
                    <Shield className="h-4 w-4" />
                    {t('admin.signIn', language)}
                  </span>
                )}
              </Button>

              <div className="rounded-lg border border-dashed border-border bg-accent/30 p-3 text-center">
                <p className="text-xs text-muted-foreground">
                  Demo: <span className="font-mono font-semibold">admin@needyfy.com</span> / <span className="font-mono font-semibold">Needyfy@2025</span>
                </p>
                <p className="mt-1 text-[10px] text-muted-foreground/60">
                  Or: <span className="font-mono font-semibold">superadmin@needyfy.com</span> / <span className="font-mono font-semibold">SuperAdmin@2025</span>
                </p>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

// ============ STAT CARD ============
function StatCard({
  title,
  value,
  change,
  icon: Icon,
  trend,
}: {
  title: string;
  value: string | number;
  change?: string;
  icon: React.ElementType;
  trend?: 'up' | 'down' | 'neutral';
}) {
  return (
    <Card className="transition-shadow hover:shadow-md">
      <CardContent className="p-4">
        <div className="flex items-start justify-between">
          <div className="space-y-1">
            <p className="text-xs font-medium text-muted-foreground">{title}</p>
            <p className="text-2xl font-bold tracking-tight">{value}</p>
            {change && (
              <div className="flex items-center gap-1">
                {trend === 'up' && <TrendingUp className="h-3 w-3 text-emerald-500" />}
                {trend === 'down' && <TrendingDown className="h-3 w-3 text-red-500" />}
                <span
                  className={`text-xs font-medium ${
                    trend === 'up'
                      ? 'text-emerald-600 dark:text-emerald-400'
                      : trend === 'down'
                      ? 'text-red-600 dark:text-red-400'
                      : 'text-muted-foreground'
                  }`}
                >
                  {change}
                </span>
              </div>
            )}
          </div>
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10">
            <Icon className="h-5 w-5 text-primary" strokeWidth={1.75} />
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

// ============ ADMIN DASHBOARD ============
function AdminDashboard({ stats, error, onNavigate }: { stats: DashboardStats | null; error?: boolean; onNavigate?: (tab: string) => void }) {
  const { language } = useAppStore();

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center gap-3 py-20">
        <XCircle className="h-10 w-10 text-destructive" />
        <p className="text-sm text-muted-foreground">
          {language === 'en' ? 'Failed to load dashboard data. Please refresh.' : 'ড্যাশবোর্ড ডেটা লোড করতে ব্যর্থ। রিফ্রেশ করুন।'}
        </p>
        <Button variant="outline" size="sm" onClick={() => window.location.reload()}>
          {language === 'en' ? 'Retry' : 'আবার চেষ্টা করুন'}
        </Button>
      </div>
    );
  }

  if (!stats) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Welcome Banner */}
      <Card className="overflow-hidden border-0 bg-gradient-to-r from-orange-600 via-orange-500 to-amber-500 shadow-lg">
        <CardContent className="flex items-center justify-between p-6">
          <div>
            <h2 className="text-xl font-bold text-white">
              {t('admin.welcome', language)} 👋
            </h2>
            <p className="mt-1 text-sm text-white/80">
              {t('admin.overview', language)} - {t('admin.thisMonth', language)}
            </p>
          </div>
          <div className="hidden sm:flex">
            <BarChart3 className="h-12 w-12 text-white/30" strokeWidth={1.5} />
          </div>
        </CardContent>
      </Card>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
        <StatCard
          title={t('admin.totalUsers', language)}
          value={stats.totalUsers}
          change="+12%"
          trend="up"
          icon={Users}
        />
        <StatCard
          title={t('admin.totalHouses', language)}
          value={stats.totalHouses}
          change="+8%"
          trend="up"
          icon={Building2}
        />
        <StatCard
          title={t('admin.totalShops', language)}
          value={stats.totalShops}
          change="+5%"
          trend="up"
          icon={Store}
        />
        <StatCard
          title={t('admin.totalProducts', language)}
          value={stats.totalProducts}
          change="+15%"
          trend="up"
          icon={ShoppingBag}
        />
        <StatCard
          title={t('admin.totalOrders', language)}
          value={stats.totalOrders}
          change="+22%"
          trend="up"
          icon={Package}
        />
        <StatCard
          title={t('admin.totalRevenue', language)}
          value={`৳${stats.totalRevenue.toLocaleString()}`}
          change="+18%"
          trend="up"
          icon={DollarSign}
        />
      </div>

      {/* Quick Actions */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-sm font-semibold">
            {t('admin.quickActions', language)}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-6">
            {[
              { icon: Plus, label: t('admin.addUser', language), color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30 dark:text-orange-400', tab: 'users' },
              { icon: Plus, label: t('admin.addListing', language), color: 'text-emerald-600 bg-emerald-50 dark:bg-emerald-950/30 dark:text-emerald-400', tab: 'houses' },
              { icon: Plus, label: t('admin.addQuestion', language), color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30 dark:text-orange-400', tab: 'mcq' },
              { icon: Bell, label: t('admin.sendNotification', language), color: 'text-amber-600 bg-amber-50 dark:bg-amber-950/30 dark:text-amber-400', tab: 'notifications' },
              { icon: Package, label: language === 'en' ? 'View Orders' : 'অর্ডার দেখুন', color: 'text-rose-600 bg-rose-50 dark:bg-rose-950/30 dark:text-rose-400', tab: 'orders' },
              { icon: Users, label: language === 'en' ? 'View Users' : 'ব্যবহারকারী দেখুন', color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30 dark:text-orange-400', tab: 'users' },
            ].map((action, i) => (
              <button
                key={i}
                onClick={() => onNavigate?.(action.tab)}
                className="flex items-center gap-2 rounded-lg border p-3 text-left transition-colors hover:bg-accent"
              >
                <div className={`flex h-8 w-8 items-center justify-center rounded-lg ${action.color}`}>
                  <action.icon className="h-4 w-4" />
                </div>
                <span className="text-xs font-medium">{action.label}</span>
              </button>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Recent Activity */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-sm font-semibold">
            {t('admin.recentActivity', language)}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {stats.recentActivity.map((activity, i) => (
              <div key={i} className="flex items-center gap-3 rounded-lg bg-accent/30 p-3">
                <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${
                  activity.type === 'user' ? 'bg-orange-100 text-orange-600 dark:bg-orange-950/30 dark:text-orange-400' :
                  activity.type === 'order' ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-950/30 dark:text-emerald-400' :
                  activity.type === 'listing' ? 'bg-amber-100 text-amber-600 dark:bg-amber-950/30 dark:text-amber-400' :
                  'bg-orange-100 text-orange-600 dark:bg-orange-950/30 dark:text-orange-400'
                }`}>
                  {activity.type === 'user' ? <Users className="h-4 w-4" /> :
                   activity.type === 'order' ? <Package className="h-4 w-4" /> :
                   activity.type === 'listing' ? <Building2 className="h-4 w-4" /> :
                   <Activity className="h-4 w-4" />}
                </div>
                <div className="flex-1 overflow-hidden">
                  <p className="truncate text-sm font-medium">{activity.title}</p>
                  <p className="text-xs text-muted-foreground">{activity.description}</p>
                </div>
                <span className="shrink-0 text-[10px] text-muted-foreground">{activity.time}</span>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

// ============ ADMIN USERS ============
function AdminUsers() {
  const { language } = useAppStore();
  const [users, setUsers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');

  const fetchUsers = useCallback(async () => {
    try {
      const res = await adminFetch('/api/admin/users');
      const data = await res.json();
      if (data.success) setUsers(data.users);
    } catch (err) {
      console.error('Failed to fetch users:', err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleToggleActive = async (userId: string, currentActive: boolean) => {
    try {
      const res = await adminFetch('/api/admin/users', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId, isActive: !currentActive }),
      });
      const data = await res.json();
      if (data.success) fetchUsers();
    } catch (err) {
      console.error('Failed to update user:', err);
    }
  };

  const handleDelete = async (userId: string) => {
    try {
      const res = await adminFetch('/api/admin/users', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId }),
      });
      const data = await res.json();
      if (data.success) fetchUsers();
    } catch (err) {
      console.error('Failed to delete user:', err);
    }
  };

  const filtered = users.filter((u) =>
    u.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    u.email.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder={language === 'en' ? 'Search users...' : 'ব্যবহারকারী খুঁজুন...'}
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-9"
          />
        </div>
        <Dialog>
          <DialogTrigger asChild>
            <Button size="sm" className="gap-1">
              <Plus className="h-4 w-4" />
              <span className="hidden sm:inline">{t('admin.addUser', language)}</span>
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t('admin.addUser', language)}</DialogTitle>
            </DialogHeader>
            <AddUserForm onUserAdded={fetchUsers} />
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t('admin.name', language)}</TableHead>
                  <TableHead className="hidden sm:table-cell">{t('admin.emailCol', language)}</TableHead>
                  <TableHead>{t('admin.role', language)}</TableHead>
                  <TableHead className="hidden md:table-cell">{t('admin.status', language)}</TableHead>
                  <TableHead className="hidden lg:table-cell">{t('admin.joined', language)}</TableHead>
                  <TableHead>{t('admin.actions', language)}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filtered.map((user) => (
                  <TableRow key={user.id}>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-xs font-bold text-primary">
                          {user.name.charAt(0).toUpperCase()}
                        </div>
                        <div>
                          <p className="text-sm font-medium">{user.name}</p>
                          <p className="text-xs text-muted-foreground sm:hidden">{user.email}</p>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="hidden text-sm sm:table-cell">{user.email}</TableCell>
                    <TableCell>
                      <Badge variant="outline" className="text-[10px]">
                        {user.roles || 'general'}
                      </Badge>
                    </TableCell>
                    <TableCell className="hidden md:table-cell">
                      <Badge
                        variant={user.isActive ? 'default' : 'secondary'}
                        className={`text-[10px] ${
                          user.isActive
                            ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400'
                            : 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400'
                        }`}
                      >
                        {user.isActive ? t('admin.active', language) : t('admin.inactive', language)}
                      </Badge>
                      {user.isVerified && (
                        <CheckCircle className="ml-1 inline h-3 w-3 text-emerald-500" />
                      )}
                    </TableCell>
                    <TableCell className="hidden text-xs text-muted-foreground lg:table-cell">
                      {new Date(user.createdAt).toLocaleDateString()}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-7 w-7"
                          onClick={() => handleToggleActive(user.id, user.isActive)}
                          title={user.isActive ? t('admin.suspend', language) : t('admin.approve', language)}
                        >
                          {user.isActive ? (
                            <Ban className="h-3.5 w-3.5 text-amber-500" />
                          ) : (
                            <CheckCircle className="h-3.5 w-3.5 text-emerald-500" />
                          )}
                        </Button>
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-7 w-7">
                              <Trash2 className="h-3.5 w-3.5 text-destructive" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>{t('admin.deleteConfirm', language)}</AlertDialogTitle>
                              <AlertDialogDescription>
                                {language === 'en'
                                  ? `This will permanently delete ${user.name}'s account and all associated data.`
                                  : `এটি ${user.name}-এর অ্যাকাউন্ট এবং সম্পর্কিত সমস্ত ডেটা স্থায়ীভাবে মুছে ফেলবে।`}
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>{t('common.cancel', language)}</AlertDialogCancel>
                              <AlertDialogAction
                                onClick={() => handleDelete(user.id)}
                                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                              >
                                {t('common.delete', language)}
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
                {filtered.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={6} className="py-8 text-center text-sm text-muted-foreground">
                      {t('common.noResults', language)}
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

// ============ ADD USER FORM ============
function AddUserForm({ onUserAdded }: { onUserAdded: () => void }) {
  const { language } = useAppStore();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [roles, setRoles] = useState('general');
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      const res = await adminFetch('/api/admin/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, email, phone, password, roles }),
      });
      const data = await res.json();
      if (data.success) {
        onUserAdded();
        setName(''); setEmail(''); setPhone(''); setPassword(''); setRoles('general');
      }
    } catch (err) {
      console.error('Failed to add user:', err);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-3">
      <div className="space-y-1">
        <Label className="text-xs">{t('admin.name', language)}</Label>
        <Input value={name} onChange={(e) => setName(e.target.value)} required />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">{t('admin.emailCol', language)}</Label>
        <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">{t('auth.phone', language)}</Label>
        <Input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">{t('auth.password', language)}</Label>
        <Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">{t('admin.role', language)}</Label>
        <select
          value={roles}
          onChange={(e) => setRoles(e.target.value)}
          className="w-full rounded-md border bg-background px-3 py-2 text-sm"
        >
          <option value="general">General User</option>
          <option value="student">Student</option>
          <option value="houseOwner">House Owner</option>
          <option value="shopOwner">Shop Owner</option>
          <option value="admin">Admin</option>
        </select>
      </div>
      <Button type="submit" className="w-full" disabled={isLoading}>
        {isLoading ? t('common.loading', language) : t('common.save', language)}
      </Button>
    </form>
  );
}

// ============ ADMIN LISTINGS ============
function AdminListings({ type }: { type: 'houses' | 'shops' | 'products' }) {
  const { language } = useAppStore();
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');

  const fetchItems = useCallback(async () => {
    try {
      const res = await adminFetch(`/api/admin/listings?type=${type}`);
      const data = await res.json();
      if (data.success) setItems(data.items);
    } catch (err) {
      console.error('Failed to fetch listings:', err);
    } finally {
      setLoading(false);
    }
  }, [type]);

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

  const handleToggleAvailable = async (id: string, current: boolean) => {
    try {
      const res = await adminFetch('/api/admin/listings', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, type, isAvailable: !current }),
      });
      const data = await res.json();
      if (data.success) fetchItems();
    } catch (err) {
      console.error('Failed to update listing:', err);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      const res = await adminFetch('/api/admin/listings', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, type }),
      });
      const data = await res.json();
      if (data.success) fetchItems();
    } catch (err) {
      console.error('Failed to delete listing:', err);
    }
  };

  const filtered = items.filter((item) =>
    item.title.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="relative">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <Input
          placeholder={language === 'en' ? 'Search listings...' : 'তালিকা খুঁজুন...'}
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="pl-9"
        />
      </div>

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {filtered.map((item) => (
          <Card key={item.id} className="overflow-hidden transition-shadow hover:shadow-md">
            <div className="h-32 bg-gradient-to-br from-primary/10 to-primary/5 flex items-center justify-center">
              {type === 'houses' ? <Building2 className="h-10 w-10 text-primary/40" strokeWidth={1.5} /> :
               type === 'shops' ? <Store className="h-10 w-10 text-primary/40" strokeWidth={1.5} /> :
               <ShoppingBag className="h-10 w-10 text-primary/40" strokeWidth={1.5} />}
            </div>
            <CardContent className="p-3">
              <h3 className="truncate text-sm font-semibold">{item.title}</h3>
              <p className="mt-1 text-xs text-muted-foreground line-clamp-2">{item.description?.slice(0, 80)}...</p>
              <div className="mt-2 flex items-center justify-between">
                <span className="text-sm font-bold text-primary">৳{item.price?.toLocaleString()}{type !== 'products' ? '/mo' : ''}</span>
                <Badge
                  variant={item.isAvailable ? 'default' : 'secondary'}
                  className={`text-[10px] ${
                    item.isAvailable
                      ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400'
                      : 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400'
                  }`}
                >
                  {item.isAvailable ? t('admin.active', language) : t('admin.inactive', language)}
                </Badge>
              </div>
              <div className="mt-3 flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  className="flex-1 text-xs"
                  onClick={() => handleToggleAvailable(item.id, item.isAvailable)}
                >
                  {item.isAvailable ? t('admin.suspend', language) : t('admin.approve', language)}
                </Button>
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="outline" size="sm" className="text-xs text-destructive hover:bg-destructive/5">
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>{t('admin.deleteConfirm', language)}</AlertDialogTitle>
                      <AlertDialogDescription>
                        {language === 'en'
                          ? `This will permanently delete "${item.title}".`
                          : `এটি "${item.title}" স্থায়ীভাবে মুছে ফেলবে।`}
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>{t('common.cancel', language)}</AlertDialogCancel>
                      <AlertDialogAction
                        onClick={() => handleDelete(item.id)}
                        className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                      >
                        {t('common.delete', language)}
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              </div>
            </CardContent>
          </Card>
        ))}
        {filtered.length === 0 && (
          <div className="col-span-full py-12 text-center text-sm text-muted-foreground">
            {t('common.noResults', language)}
          </div>
        )}
      </div>
    </div>
  );
}

// ============ ADMIN ORDERS ============
function AdminOrders() {
  const { language } = useAppStore();
  const [orders, setOrders] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterStatus, setFilterStatus] = useState('all');

  const fetchOrders = useCallback(async () => {
    try {
      const res = await adminFetch('/api/admin/orders');
      const data = await res.json();
      if (data.success) setOrders(data.orders);
    } catch (err) {
      console.error('Failed to fetch orders:', err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleUpdateStatus = async (orderId: string, status: string) => {
    try {
      const res = await adminFetch('/api/admin/orders', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ orderId, status }),
      });
      const data = await res.json();
      if (data.success) fetchOrders();
    } catch (err) {
      console.error('Failed to update order:', err);
    }
  };

  const filtered = filterStatus === 'all'
    ? orders
    : orders.filter((o) => o.status === filterStatus);

  const statusColors: Record<string, string> = {
    pending: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
    confirmed: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
    shipped: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
    delivered: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400',
    cancelled: 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400',
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex gap-2 overflow-x-auto pb-1">
        {['all', 'pending', 'confirmed', 'shipped', 'delivered', 'cancelled'].map((status) => (
          <Button
            key={status}
            variant={filterStatus === status ? 'default' : 'outline'}
            size="sm"
            className="shrink-0 text-xs"
            onClick={() => setFilterStatus(status)}
          >
            {status === 'all' ? (language === 'en' ? 'All' : 'সব') :
             t(`order.${status as 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled'}`, language)}
          </Button>
        ))}
      </div>

      <div className="grid gap-3 sm:grid-cols-2">
        {filtered.map((order) => (
          <Card key={order.id} className="transition-shadow hover:shadow-md">
            <CardContent className="p-4">
              <div className="flex items-start justify-between">
                <div>
                  <p className="text-xs font-mono text-muted-foreground">{order.id.slice(0, 12)}...</p>
                  <p className="mt-1 text-sm font-semibold">৳{order.totalAmount?.toLocaleString()}</p>
                  <p className="text-xs text-muted-foreground">{order.address?.slice(0, 40)}...</p>
                </div>
                <Badge className={`text-[10px] ${statusColors[order.status] || ''}`}>
                  {t(`order.${order.status as 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled'}`, language)}
                </Badge>
              </div>
              <Separator className="my-3" />
              <div className="flex items-center gap-2">
                {order.status === 'pending' && (
                  <>
                    <Button
                      size="sm"
                      variant="outline"
                      className="flex-1 text-xs text-emerald-600 hover:bg-emerald-50 dark:hover:bg-emerald-950/30"
                      onClick={() => handleUpdateStatus(order.id, 'confirmed')}
                    >
                      <CheckCircle className="mr-1 h-3 w-3" />
                      {t('admin.approve', language)}
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      className="flex-1 text-xs text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30"
                      onClick={() => handleUpdateStatus(order.id, 'cancelled')}
                    >
                      <XCircle className="mr-1 h-3 w-3" />
                      {t('admin.reject', language)}
                    </Button>
                  </>
                )}
                {order.status === 'confirmed' && (
                  <Button
                    size="sm"
                    variant="outline"
                    className="w-full text-xs"
                    onClick={() => handleUpdateStatus(order.id, 'shipped')}
                  >
                    <Package className="mr-1 h-3 w-3" />
                    {language === 'en' ? 'Mark Shipped' : 'শিপড করুন'}
                  </Button>
                )}
                {order.status === 'shipped' && (
                  <Button
                    size="sm"
                    variant="outline"
                    className="w-full text-xs text-emerald-600"
                    onClick={() => handleUpdateStatus(order.id, 'delivered')}
                  >
                    <CheckCircle className="mr-1 h-3 w-3" />
                    {language === 'en' ? 'Mark Delivered' : 'ডেলিভারড করুন'}
                  </Button>
                )}
                {(order.status === 'delivered' || order.status === 'cancelled') && (
                  <span className="text-xs text-muted-foreground">
                    {language === 'en' ? 'Completed' : 'সম্পন্ন'}
                  </span>
                )}
              </div>
            </CardContent>
          </Card>
        ))}
        {filtered.length === 0 && (
          <div className="col-span-full py-12 text-center text-sm text-muted-foreground">
            {t('common.noResults', language)}
          </div>
        )}
      </div>
    </div>
  );
}

// ============ ADMIN MCQ ============
function AdminMCQ() {
  const { language } = useAppStore();
  const [questions, setQuestions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterClass, setFilterClass] = useState<string>('all');
  const [filterTopic, setFilterTopic] = useState<string>('all');

  const fetchQuestions = useCallback(async () => {
    try {
      const res = await adminFetch('/api/admin/mcq');
      const data = await res.json();
      if (data.success) setQuestions(data.questions);
    } catch (err) {
      console.error('Failed to fetch MCQ:', err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleDelete = async (id: string) => {
    try {
      const res = await adminFetch('/api/admin/mcq', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id }),
      });
      const data = await res.json();
      if (data.success) fetchQuestions();
    } catch (err) {
      console.error('Failed to delete question:', err);
    }
  };

  // Get unique classes and topics from questions for filter pills
  const availableClasses = ['all', ...Array.from(new Set(questions.map((q: any) => q.class).filter(Boolean)))];
  const availableTopics = filterClass === 'all'
    ? ['all', ...Array.from(new Set(questions.map((q: any) => q.topic).filter(Boolean)))]
    : ['all', ...(MCQ_TOPICS[filterClass]?.map((t) => t.value) || [])];

  const filtered = questions.filter((q: any) => {
    const matchesClass = filterClass === 'all' || q.class === filterClass;
    const matchesTopic = filterTopic === 'all' || q.topic === filterTopic;
    return matchesClass && matchesTopic;
  });

  // Reset topic when class filter changes
  const handleFilterClassChange = (cls: string) => {
    setFilterClass(cls);
    setFilterTopic('all');
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-sm text-muted-foreground">
          {language === 'en' ? `${filtered.length} of ${questions.length} questions` : `${questions.length} এর মধ্যে ${filtered.length} প্রশ্ন`}
        </p>
        <Dialog>
          <DialogTrigger asChild>
            <Button size="sm" className="gap-1">
              <Plus className="h-4 w-4" />
              {t('admin.addQuestion', language)}
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t('admin.addQuestion', language)}</DialogTitle>
            </DialogHeader>
            <AddMCQForm onQuestionAdded={fetchQuestions} />
          </DialogContent>
        </Dialog>
      </div>

      {/* Filter by Class */}
      <div className="space-y-2">
        <div className="flex items-center gap-2">
          <span className="shrink-0 text-[10px] font-medium text-muted-foreground">
            {language === 'en' ? 'Class:' : 'শ্রেণি:'}
          </span>
          <div className="flex gap-1.5 overflow-x-auto pb-1">
            {availableClasses.map((cls) => (
              <button
                key={cls}
                onClick={() => handleFilterClassChange(cls)}
                className={`shrink-0 rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${
                  filterClass === cls
                    ? 'border-primary bg-primary text-primary-foreground'
                    : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-primary/5'
                }`}
              >
                {cls === 'all'
                  ? (language === 'en' ? 'All' : 'সব')
                  : cls}
              </button>
            ))}
          </div>
        </div>

        {/* Filter by Topic */}
        <div className="flex items-center gap-2">
          <span className="shrink-0 text-[10px] font-medium text-muted-foreground">
            {language === 'en' ? 'Topic:' : 'বিষয়:'}
          </span>
          <div className="flex gap-1.5 overflow-x-auto pb-1">
            {availableTopics.map((topic) => (
              <button
                key={topic}
                onClick={() => setFilterTopic(topic)}
                className={`shrink-0 rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${
                  filterTopic === topic
                    ? 'border-primary bg-primary text-primary-foreground'
                    : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-primary/5'
                }`}
              >
                {topic === 'all'
                  ? (language === 'en' ? 'All' : 'সব')
                  : topic}
              </button>
            ))}
          </div>
        </div>
      </div>

      {filtered.map((q: any, i: number) => (
        <Card key={q.id} className="transition-shadow hover:shadow-md">
          <CardContent className="p-4">
            <div className="flex items-start justify-between gap-3">
              <div className="flex-1">
                <div className="flex flex-wrap items-center gap-1.5">
                  <span className="flex h-6 w-6 items-center justify-center rounded-full bg-primary/10 text-xs font-bold text-primary">
                    {i + 1}
                  </span>
                  {q.class && (
                    <Badge className={`text-[10px] ${CLASS_COLORS[q.class] || 'bg-gray-100 text-gray-700 dark:bg-gray-950/30 dark:text-gray-400'}`}>
                      {q.class}
                    </Badge>
                  )}
                  {q.topic && (
                    <Badge className={`text-[10px] ${TOPIC_COLORS[q.topic] || 'bg-gray-100 text-gray-700 dark:bg-gray-950/30 dark:text-gray-400'}`}>
                      {q.topic}
                    </Badge>
                  )}
                  <Badge variant="outline" className="text-[10px]">{q.category}</Badge>
                  <Badge variant="outline" className="text-[10px]">{q.difficulty}</Badge>
                </div>
                <p className="mt-2 text-sm font-medium">{q.question}</p>
                <div className="mt-2 grid grid-cols-2 gap-1 text-xs">
                  <span className={`rounded px-2 py-1 ${q.correctAnswer === 'A' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-accent'}`}>
                    A. {q.optionA}
                  </span>
                  <span className={`rounded px-2 py-1 ${q.correctAnswer === 'B' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-accent'}`}>
                    B. {q.optionB}
                  </span>
                  <span className={`rounded px-2 py-1 ${q.correctAnswer === 'C' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-accent'}`}>
                    C. {q.optionC}
                  </span>
                  <span className={`rounded px-2 py-1 ${q.correctAnswer === 'D' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-accent'}`}>
                    D. {q.optionD}
                  </span>
                </div>
              </div>
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0">
                    <Trash2 className="h-3.5 w-3.5 text-destructive" />
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>{t('admin.deleteConfirm', language)}</AlertDialogTitle>
                    <AlertDialogDescription>
                      {language === 'en'
                        ? 'This will permanently delete this question.'
                        : 'এটি এই প্রশ্নটি স্থায়ীভাবে মুছে ফেলবে।'}
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>{t('common.cancel', language)}</AlertDialogCancel>
                    <AlertDialogAction
                      onClick={() => handleDelete(q.id)}
                      className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                    >
                      {t('common.delete', language)}
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>
          </CardContent>
        </Card>
      ))}
      {filtered.length === 0 && (
        <div className="py-12 text-center text-sm text-muted-foreground">
          {t('common.noResults', language)}
        </div>
      )}
    </div>
  );
}

// ============ CLASS/TOPIC CONFIG ============
const MCQ_CLASSES = [
  { value: 'SSC', label: 'SSC (Class 9-10)', labelBn: 'এসএসসি (ক্লাস ৯-১০)' },
  { value: 'HSC', label: 'HSC (Class 11-12)', labelBn: 'এইচএসসি (ক্লাস ১১-১২)' },
  { value: 'Admission', label: 'Admission Test', labelBn: 'ভর্তি পরীক্ষা' },
  { value: 'GK', label: 'General Knowledge (GK)', labelBn: 'সাধারণ জ্ঞান (জিকে)' },
  { value: 'BCS', label: 'BCS Preliminary', labelBn: 'বিসিএস প্রিলিমিনারি' },
] as const;

const MCQ_TOPICS: Record<string, { value: string; label: string; labelBn: string }[]> = {
  SSC: [
    { value: 'Mathematics', label: 'Mathematics', labelBn: 'গণিত' },
    { value: 'Physics', label: 'Physics', labelBn: 'পদার্থবিজ্ঞান' },
    { value: 'Chemistry', label: 'Chemistry', labelBn: 'রসায়ন' },
    { value: 'Biology', label: 'Biology', labelBn: 'জীববিজ্ঞান' },
    { value: 'Bangla', label: 'Bangla', labelBn: 'বাংলা' },
    { value: 'English', label: 'English', labelBn: 'ইংরেজি' },
    { value: 'General Science', label: 'General Science', labelBn: 'সাধারণ বিজ্ঞান' },
    { value: 'ICT', label: 'ICT', labelBn: 'আইসিটি' },
  ],
  HSC: [
    { value: 'Mathematics', label: 'Mathematics', labelBn: 'গণিত' },
    { value: 'Physics', label: 'Physics', labelBn: 'পদার্থবিজ্ঞান' },
    { value: 'Chemistry', label: 'Chemistry', labelBn: 'রসায়ন' },
    { value: 'Biology', label: 'Biology', labelBn: 'জীববিজ্ঞান' },
    { value: 'Bangla', label: 'Bangla', labelBn: 'বাংলা' },
    { value: 'English', label: 'English', labelBn: 'ইংরেজি' },
    { value: 'Accounting', label: 'Accounting', labelBn: 'হিসাববিজ্ঞান' },
    { value: 'Management', label: 'Management', labelBn: 'ম্যানেজমেন্ট' },
    { value: 'ICT', label: 'ICT', labelBn: 'আইসিটি' },
    { value: 'Economics', label: 'Economics', labelBn: 'অর্থনীতি' },
  ],
  Admission: [
    { value: 'Mathematics', label: 'Mathematics', labelBn: 'গণিত' },
    { value: 'Physics', label: 'Physics', labelBn: 'পদার্থবিজ্ঞান' },
    { value: 'Chemistry', label: 'Chemistry', labelBn: 'রসায়ন' },
    { value: 'Biology', label: 'Biology', labelBn: 'জীববিজ্ঞান' },
    { value: 'English', label: 'English', labelBn: 'ইংরেজি' },
    { value: 'General Knowledge', label: 'General Knowledge', labelBn: 'সাধারণ জ্ঞান' },
  ],
  GK: [
    { value: 'Bangladesh Affairs', label: 'Bangladesh Affairs', labelBn: 'বাংলাদেশ বিষয়াবলী' },
    { value: 'International Affairs', label: 'International Affairs', labelBn: 'আন্তর্জাতিক বিষয়াবলী' },
    { value: 'Science & Technology', label: 'Science & Technology', labelBn: 'বিজ্ঞান ও প্রযুক্তি' },
    { value: 'History', label: 'History', labelBn: 'ইতিহাস' },
    { value: 'Geography', label: 'Geography', labelBn: 'ভূগোল' },
    { value: 'Sports', label: 'Sports', labelBn: 'খেলাধুলা' },
    { value: 'Literature', label: 'Literature', labelBn: 'সাহিত্য' },
  ],
  BCS: [
    { value: 'Bangla', label: 'Bangla', labelBn: 'বাংলা' },
    { value: 'English', label: 'English', labelBn: 'ইংরেজি' },
    { value: 'Mathematics', label: 'Mathematics', labelBn: 'গণিত' },
    { value: 'General Science', label: 'General Science', labelBn: 'সাধারণ বিজ্ঞান' },
    { value: 'Bangladesh Affairs', label: 'Bangladesh Affairs', labelBn: 'বাংলাদেশ বিষয়াবলী' },
    { value: 'International Affairs', label: 'International Affairs', labelBn: 'আন্তর্জাতিক বিষয়াবলী' },
    { value: 'Mental Ability', label: 'Mental Ability', labelBn: 'মানসিক দক্ষতা' },
    { value: 'Current Affairs', label: 'Current Affairs', labelBn: 'সাম্প্রতিক বিষয়াবলী' },
  ],
};

const CLASS_COLORS: Record<string, string> = {
  SSC: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
  HSC: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
  Admission: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
  GK: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400',
  BCS: 'bg-rose-100 text-rose-700 dark:bg-rose-950/30 dark:text-rose-400',
};

const TOPIC_COLORS: Record<string, string> = {
  Mathematics: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
  Physics: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
  Chemistry: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
  Biology: 'bg-green-100 text-green-700 dark:bg-green-950/30 dark:text-green-400',
  Bangla: 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400',
  English: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
  'General Science': 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
  ICT: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
  Accounting: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-950/30 dark:text-yellow-400',
  Management: 'bg-pink-100 text-pink-700 dark:bg-pink-950/30 dark:text-pink-400',
  Economics: 'bg-lime-100 text-lime-700 dark:bg-lime-950/30 dark:text-lime-400',
  'General Knowledge': 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400',
  'Bangladesh Affairs': 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400',
  'International Affairs': 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
  'Science & Technology': 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
  History: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
  Geography: 'bg-green-100 text-green-700 dark:bg-green-950/30 dark:text-green-400',
  Sports: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
  Literature: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400',
  'Mental Ability': 'bg-pink-100 text-pink-700 dark:bg-pink-950/30 dark:text-pink-400',
  'Current Affairs': 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
};

// ============ ADD MCQ FORM ============
function AddMCQForm({ onQuestionAdded }: { onQuestionAdded: () => void }) {
  const { language } = useAppStore();
  const [form, setForm] = useState({
    question: '', optionA: '', optionB: '', optionC: '', optionD: '',
    correctAnswer: 'A', category: 'gk', difficulty: 'medium', explanation: '',
  });
  const [selectedClass, setSelectedClass] = useState('SSC');
  const [selectedTopic, setSelectedTopic] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const availableTopics = MCQ_TOPICS[selectedClass] || [];

  const handleClassChange = (newClass: string) => {
    setSelectedClass(newClass);
    setSelectedTopic(''); // Reset topic when class changes
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      const res = await adminFetch('/api/admin/mcq', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...form,
          class: selectedClass,
          topic: selectedTopic || MCQ_TOPICS[selectedClass]?.[0]?.value || 'General',
        }),
      });
      const data = await res.json();
      if (data.success) {
        onQuestionAdded();
        setForm({ question: '', optionA: '', optionB: '', optionC: '', optionD: '', correctAnswer: 'A', category: 'gk', difficulty: 'medium', explanation: '' });
        setSelectedClass('SSC');
        setSelectedTopic('');
      }
    } catch (err) {
      console.error('Failed to add question:', err);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-3">
      <div className="grid grid-cols-2 gap-2">
        <div className="space-y-1">
          <Label className="text-xs">
            {language === 'en' ? 'Class / Level' : 'শ্রেণি / স্তর'}
          </Label>
          <select
            value={selectedClass}
            onChange={(e) => handleClassChange(e.target.value)}
            className="w-full rounded-md border bg-background px-3 py-2 text-sm"
          >
            {MCQ_CLASSES.map((cls) => (
              <option key={cls.value} value={cls.value}>
                {language === 'en' ? cls.label : cls.labelBn}
              </option>
            ))}
          </select>
        </div>
        <div className="space-y-1">
          <Label className="text-xs">
            {language === 'en' ? 'Topic / Subject' : 'বিষয় / বিষয়বস্তু'}
          </Label>
          <select
            value={selectedTopic}
            onChange={(e) => setSelectedTopic(e.target.value)}
            className="w-full rounded-md border bg-background px-3 py-2 text-sm"
          >
            <option value="">
              {language === 'en' ? 'Select Topic' : 'বিষয় নির্বাচন করুন'}
            </option>
            {availableTopics.map((topic) => (
              <option key={topic.value} value={topic.value}>
                {language === 'en' ? topic.label : topic.labelBn}
              </option>
            ))}
          </select>
        </div>
      </div>
      <div className="space-y-1">
        <Label className="text-xs">{language === 'en' ? 'Question' : 'প্রশ্ন'}</Label>
        <Input value={form.question} onChange={(e) => setForm({ ...form, question: e.target.value })} required />
      </div>
      <div className="grid grid-cols-2 gap-2">
        <div className="space-y-1">
          <Label className="text-xs">Option A</Label>
          <Input value={form.optionA} onChange={(e) => setForm({ ...form, optionA: e.target.value })} required />
        </div>
        <div className="space-y-1">
          <Label className="text-xs">Option B</Label>
          <Input value={form.optionB} onChange={(e) => setForm({ ...form, optionB: e.target.value })} required />
        </div>
        <div className="space-y-1">
          <Label className="text-xs">Option C</Label>
          <Input value={form.optionC} onChange={(e) => setForm({ ...form, optionC: e.target.value })} required />
        </div>
        <div className="space-y-1">
          <Label className="text-xs">Option D</Label>
          <Input value={form.optionD} onChange={(e) => setForm({ ...form, optionD: e.target.value })} required />
        </div>
      </div>
      <div className="grid grid-cols-3 gap-2">
        <div className="space-y-1">
          <Label className="text-xs">Correct Answer</Label>
          <select value={form.correctAnswer} onChange={(e) => setForm({ ...form, correctAnswer: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
            <option value="A">A</option><option value="B">B</option><option value="C">C</option><option value="D">D</option>
          </select>
        </div>
        <div className="space-y-1">
          <Label className="text-xs">Category</Label>
          <select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
            <option value="gk">GK</option><option value="ssc">SSC</option><option value="hsc">HSC</option><option value="admission">Admission</option>
          </select>
        </div>
        <div className="space-y-1">
          <Label className="text-xs">Difficulty</Label>
          <select value={form.difficulty} onChange={(e) => setForm({ ...form, difficulty: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
            <option value="easy">Easy</option><option value="medium">Medium</option><option value="hard">Hard</option>
          </select>
        </div>
      </div>
      <div className="space-y-1">
        <Label className="text-xs">{t('edu.explanation', language)}</Label>
        <Input value={form.explanation} onChange={(e) => setForm({ ...form, explanation: e.target.value })} />
      </div>
      <Button type="submit" className="w-full" disabled={isLoading}>
        {isLoading ? t('common.loading', language) : t('common.save', language)}
      </Button>
    </form>
  );
}

// ============ ADMIN COMMUNITY ============
function AdminCommunity() {
  const { language } = useAppStore();
  const [posts, setPosts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchPosts = useCallback(async () => {
    try {
      const res = await adminFetch('/api/admin/community');
      const data = await res.json();
      if (data.success) setPosts(data.posts);
    } catch (err) {
      console.error('Failed to fetch posts:', err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleDelete = async (id: string) => {
    try {
      const res = await adminFetch('/api/admin/community', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id }),
      });
      const data = await res.json();
      if (data.success) fetchPosts();
    } catch (err) {
      console.error('Failed to delete post:', err);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {posts.map((post) => (
        <Card key={post.id} className="transition-shadow hover:shadow-md">
          <CardContent className="p-4">
            <div className="flex items-start justify-between gap-3">
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="text-[10px]">{post.postType}</Badge>
                  <span className="text-xs text-muted-foreground">
                    ❤️ {post.likes} {language === 'en' ? 'likes' : 'লাইক'}
                  </span>
                </div>
                <h3 className="mt-1 text-sm font-semibold">{post.title}</h3>
                <p className="mt-1 text-xs text-muted-foreground line-clamp-2">{post.content}</p>
                <p className="mt-2 text-[10px] text-muted-foreground">
                  {new Date(post.createdAt).toLocaleDateString()}
                </p>
              </div>
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0">
                    <Trash2 className="h-3.5 w-3.5 text-destructive" />
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>{t('admin.deleteConfirm', language)}</AlertDialogTitle>
                    <AlertDialogDescription>
                      {language === 'en'
                        ? 'This will permanently delete this post.'
                        : 'এটি এই পোস্টটি স্থায়ীভাবে মুছে ফেলবে।'}
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>{t('common.cancel', language)}</AlertDialogCancel>
                    <AlertDialogAction
                      onClick={() => handleDelete(post.id)}
                      className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                    >
                      {t('common.delete', language)}
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>
          </CardContent>
        </Card>
      ))}
      {posts.length === 0 && (
        <div className="py-12 text-center text-sm text-muted-foreground">
          {t('common.noResults', language)}
        </div>
      )}
    </div>
  );
}

// ============ ADMIN SETTINGS (redirects to AdminCustomizer) ============
// The full customization panel is now imported from AdminSettings.tsx

// ============ TYPES ============
interface DashboardStats {
  totalUsers: number;
  totalHouses: number;
  totalShops: number;
  totalProducts: number;
  totalOrders: number;
  totalRevenue: number;
  recentActivity: {
    type: string;
    title: string;
    description: string;
    time: string;
  }[];
}

// ============ MAIN ADMIN MODULE ============
export default function AdminModule() {
  const {
    language,
    isAdminLoggedIn,
    adminUser,
    adminLogout,
    adminTab,
    setAdminTab,
    adminToken,
  } = useAppStore();

  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [statsError, setStatsError] = useState(false);

  useEffect(() => {
    if (isAdminLoggedIn && adminTab === 'dashboard') {
      adminFetch('/api/admin/stats')
        .then((res) => {
          if (res.status === 401) {
            // Token invalid - adminLogout is called by adminFetch
            return null;
          }
          return res.json();
        })
        .then((data) => {
          if (data?.success) {
            setStats(data.stats);
            setStatsError(false);
          } else {
            setStatsError(true);
          }
        })
        .catch(() => {
          setStatsError(true);
        });
    }
  }, [isAdminLoggedIn, adminTab, adminToken]);

  // Show login if not authenticated
  if (!isAdminLoggedIn) {
    return <AdminLogin />;
  }

  const tabs = [
    { id: 'dashboard', label: t('admin.dashboard', language), icon: LayoutDashboard },
    { id: 'users', label: t('admin.users', language), icon: Users },
    { id: 'houses', label: t('admin.houses', language), icon: Building2 },
    { id: 'shops', label: t('admin.shops', language), icon: Store },
    { id: 'products', label: t('admin.products', language), icon: ShoppingBag },
    { id: 'orders', label: t('admin.orders', language), icon: Package },
    { id: 'mcq', label: t('admin.mcq', language), icon: GraduationCap },
    { id: 'community', label: t('admin.community', language), icon: MessageSquare },
    { id: 'teams', label: language === 'en' ? 'Teams' : 'টিম', icon: UsersRound },
    { id: 'roles', label: language === 'en' ? 'Roles' : 'ভূমিকা', icon: Crown },
    { id: 'menus', label: language === 'en' ? 'Menus' : 'মেনু', icon: MenuIcon },
    { id: 'notifications', label: language === 'en' ? 'Notifications' : 'নোটিফিকেশন', icon: Bell },
    { id: 'customizer', label: language === 'en' ? 'Customizer' : 'কাস্টমাইজার', icon: Palette },
    { id: 'payment-gateways', label: language === 'en' ? 'Payment Gateways' : 'পেমেন্ট গেটওয়ে', icon: CreditCard },
    { id: 'server', label: language === 'en' ? 'Server' : 'সার্ভার', icon: ServerIcon },
    { id: 'settings', label: t('admin.settings', language), icon: Settings },
  ];

  const renderContent = () => {
    switch (adminTab) {
      case 'dashboard': return <AdminDashboard stats={stats} error={statsError} onNavigate={setAdminTab} />;
      case 'users': return <AdminUsers />;
      case 'houses': return <AdminListings type="houses" />;
      case 'shops': return <AdminListings type="shops" />;
      case 'products': return <AdminListings type="products" />;
      case 'orders': return <AdminOrders />;
      case 'mcq': return <AdminMCQManager />;
      case 'community': return <AdminCommunity />;
      case 'teams': return <AdminTeams />;
      case 'roles': return <AdminRoles />;
      case 'menus': return <AdminMenus />;
      case 'notifications': return <AdminNotifications />;
      case 'customizer': return <AdminCustomizer />;
      case 'payment-gateways': return <AdminPayments />;
      case 'server': return <AdminServer />;
      case 'settings': return <AdminCustomizer />;
      default: return <AdminDashboard stats={stats} error={statsError} onNavigate={setAdminTab} />;
    }
  };

  return (
    <div className="flex min-h-screen">
      {/* Admin Sidebar */}
      <aside className="hidden w-56 shrink-0 border-r bg-card lg:block">
        <div className="flex h-full flex-col">
          {/* Admin Profile */}
          <div className="border-b p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-orange-600 to-amber-500 shadow-md">
                <Shield className="h-5 w-5 text-white" />
              </div>
              <div className="flex-1 overflow-hidden">
                <p className="truncate text-sm font-semibold">{adminUser?.name || 'Admin'}</p>
                <p className="truncate text-[10px] text-muted-foreground">{adminUser?.email}</p>
              </div>
            </div>
          </div>

          {/* Nav Items */}
          <nav className="flex-1 overflow-y-auto p-2 custom-scrollbar">
            <div className="space-y-0.5">
              {tabs.map((tab) => {
                const Icon = tab.icon;
                const isActive = adminTab === tab.id;
                return (
                  <button
                    key={tab.id}
                    onClick={() => setAdminTab(tab.id)}
                    className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm transition-colors duration-150 ${
                      isActive
                        ? 'bg-primary/10 font-medium text-primary'
                        : 'text-foreground/70 hover:bg-accent hover:text-foreground'
                    }`}
                  >
                    <Icon className={`h-4 w-4 ${isActive ? 'text-primary' : ''}`} strokeWidth={isActive ? 2.5 : 2} />
                    <span>{tab.label}</span>
                  </button>
                );
              })}
            </div>
          </nav>

          {/* Back to App + Logout */}
          <div className="border-t p-2 space-y-0.5">
            <button
              onClick={() => useAppStore.getState().setCurrentSection('home')}
              className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-orange-600 transition-colors hover:bg-orange-50 hover:text-orange-700 dark:text-orange-400 dark:hover:bg-orange-950/30 dark:hover:text-orange-300"
            >
              <ArrowLeft className="h-4 w-4" />
              <span>{language === 'en' ? 'Back to App' : 'অ্যাপে ফিরুন'}</span>
            </button>
            <button
              onClick={adminLogout}
              className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-destructive transition-colors hover:bg-destructive/5"
            >
              <LogOut className="h-4 w-4" />
              <span>{t('admin.logout', language)}</span>
            </button>
          </div>
        </div>
      </aside>

      {/* Mobile Tab Bar */}
      <div className="fixed bottom-16 left-0 right-0 z-30 border-t bg-background/95 backdrop-blur lg:hidden">
        <div className="flex overflow-x-auto px-2 py-1.5 gap-0.5">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            const isActive = adminTab === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => setAdminTab(tab.id)}
                className={`flex shrink-0 flex-col items-center gap-0.5 rounded-lg px-2.5 py-1.5 text-[10px] transition-colors ${
                  isActive
                    ? 'bg-primary/10 text-primary font-medium'
                    : 'text-muted-foreground hover:bg-accent'
                }`}
              >
                <Icon className="h-4 w-4" strokeWidth={isActive ? 2.5 : 1.75} />
                <span>{tab.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Main Content */}
      <div className="flex-1 overflow-y-auto custom-scrollbar">
        {/* Mobile Admin Header */}
        <div className="sticky top-0 z-20 flex items-center justify-between border-b bg-background/95 px-4 py-2.5 backdrop-blur lg:hidden">
          <div className="flex items-center gap-2">
            <Shield className="h-5 w-5 text-primary" />
            <span className="text-sm font-semibold">{tabs.find((t) => t.id === adminTab)?.label}</span>
          </div>
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="sm"
              className="gap-1 text-xs text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30"
              onClick={() => useAppStore.getState().setCurrentSection('home')}
            >
              <ArrowLeft className="h-3.5 w-3.5" />
              <span className="hidden sm:inline">{language === 'en' ? 'Back to App' : 'অ্যাপে ফিরুন'}</span>
              <span className="sm:hidden">{language === 'en' ? 'App' : 'অ্যাপ'}</span>
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className="text-xs text-destructive hover:bg-destructive/5"
              onClick={adminLogout}
            >
              <LogOut className="mr-1 h-3.5 w-3.5" />
              {t('admin.logout', language)}
            </Button>
          </div>
        </div>

        <div className="p-4 pb-20 lg:pb-4">
          {/* Back to Dashboard button for sub-pages */}
          {adminTab !== 'dashboard' && (
            <div className="mb-4">
              <Button
                variant="ghost"
                size="sm"
                className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30"
                onClick={() => setAdminTab('dashboard')}
              >
                <ArrowLeft className="h-4 w-4" />
                <span>{language === 'en' ? 'Back to Dashboard' : 'ড্যাশবোর্ডে ফিরুন'}</span>
              </Button>
            </div>
          )}
          {renderContent()}
        </div>
      </div>
    </div>
  );
}
