'use client';

import { useState, useEffect, useCallback } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import {
  BarChart3,
  Building2,
  Users,
  UserPlus,
  Settings,
  Plus,
  Pencil,
  Trash2,
  Loader2,
  Search,
  RefreshCw,
  UsersRound,
  Vote,
  CheckCircle2,
  XCircle,
  Shield,
  UserCheck,
  ToggleLeft,
  Eye,
  Clock,
  Hash,
  Type,
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from '@/components/ui/tabs';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import { Progress } from '@/components/ui/progress';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';

// ==================== Types ====================
interface Branch {
  id: string;
  name: string;
  code: string;
  createdAt?: string;
  employeeCount?: number;
}

interface Employee {
  id: string;
  employeeId: string;
  name: string;
  branchId: string;
  branchName: string;
  branchCode: string;
  isAdmin: boolean;
  isActive: boolean;
  createdAt: string;
}

interface Candidate {
  id: string;
  employeeId: string;
  branchId: string;
  position: string | null;
  statement: string | null;
  photoUrl: string | null;
  isApproved: boolean;
  createdAt: string;
  name: string;
  employeeCode: string;
  branchName: string;
  branchCode: string;
}

interface BranchStats {
  branchId: string;
  branchName: string;
  branchCode: string;
  totalEligibleVoters: number;
  totalVoters: number;
  participationRate: number;
  totalVotes: number;
}

interface Stats {
  totalEmployees: number;
  totalVoters: number;
  totalCandidates: number;
  totalVotes: number;
  overallParticipation: number;
  votesByBranch: BranchStats[];
}

interface AppSettings {
  [key: string]: string;
}

// ==================== Zod Schemas ====================
const branchSchema = z.object({
  name: z.string().min(1, 'กรุณาระบุชื่อสาขา'),
  code: z.string().min(1, 'กรุณาระบุรหัสสาขา'),
});

const employeeSchema = z.object({
  employeeId: z.string().min(1, 'กรุณาระบุรหัสพนักงาน'),
  name: z.string().min(1, 'กรุณาระบุชื่อพนักงาน'),
  branchId: z.string().min(1, 'กรุณาเลือกสาขา'),
  pin: z.string().min(4, 'PIN ต้องมีอย่างน้อย 4 ตัวอักษร'),
  isAdmin: z.boolean().default(false),
});

const employeeEditSchema = z.object({
  name: z.string().min(1, 'กรุณาระบุชื่อพนักงาน'),
  branchId: z.string().min(1, 'กรุาเลือกสาขา'),
  pin: z.string().optional(),
  isAdmin: z.boolean().default(false),
  isActive: z.boolean().default(true),
});

const candidateSchema = z.object({
  employeeId: z.string().min(1, 'กรุณาเลือกพนักงาน'),
  branchId: z.string().min(1, 'กรุณาระบุสาขา'),
});

const settingsSchema = z.object({
  maxVotesPerPerson: z.string().min(1, 'กรุณาระบุจำนวนคะแนนสูงสุด'),
  votingStartDate: z.string().min(1, 'กรุณาระบุวันเริ่มต้น'),
  votingEndDate: z.string().min(1, 'กรุณาระบุวันสิ้นสุด'),
  votingEnabled: z.boolean().default(false),
  resultsVisible: z.boolean().default(false),
  systemName: z.string().min(1, 'กรุณาระบุชื่อระบบ'),
});

type BranchFormValues = z.infer<typeof branchSchema>;
type EmployeeFormValues = z.infer<typeof employeeSchema>;
type EmployeeEditFormValues = z.infer<typeof employeeEditSchema>;
type CandidateFormValues = z.infer<typeof candidateSchema>;
type SettingsFormValues = z.infer<typeof settingsSchema>;

// ==================== Helper Functions ====================
function formatDate(dateStr: string): string {
  if (!dateStr) return '—';
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('th-TH', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  } catch {
    return dateStr;
  }
}

function formatDateTimeLocal(dateStr: string): string {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    const pad = (n: number) => n.toString().padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
  } catch {
    return '';
  }
}

async function apiFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  });
  const data = await res.json().catch(() => null);
  if (!res.ok || data?.success === false) {
    throw new Error(data?.error || 'เกิดข้อผิดพลาดในระบบ');
  }
  return data;
}

// ==================== Skeleton Components ====================
function StatsSkeleton() {
  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
        {Array.from({ length: 5 }).map((_, i) => (
          <Skeleton key={i} className="h-28 rounded-xl" />
        ))}
      </div>
      <Skeleton className="h-64 rounded-xl" />
    </div>
  );
}

function TableSkeleton({ rows = 5 }: { rows?: number }) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <Skeleton className="h-10 w-64" />
        <Skeleton className="h-10 w-32" />
      </div>
      <div className="rounded-xl border">
        <div className="p-4 space-y-3">
          {Array.from({ length: rows }).map((_, i) => (
            <Skeleton key={i} className="h-12 w-full" />
          ))}
        </div>
      </div>
    </div>
  );
}

// ==================== Tab 1: สถิติ (Statistics) ====================
function StatsTab() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStats = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await apiFetch<{ success: boolean; stats: Stats }>('/api/admin/stats');
      setStats(data.stats);
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'เกิดข้อผิดพลาดในระบบ';
      setError(msg);
      toast.error('ไม่สามารถโหลดสถิติได้', { description: msg });
    } finally {
      setLoading(false);
    }
  }, []);

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

  if (loading) return <StatsSkeleton />;

  if (error || !stats) {
    return (
      <Card className="border-red-200 dark:border-red-800/50">
        <CardContent className="p-6 text-center">
          <p className="text-red-600 dark:text-red-400 mb-4">{error || 'ไม่สามารถโหลดข้อมูลได้'}</p>
          <Button onClick={fetchStats} variant="outline" className="border-emerald-300 dark:border-emerald-700 text-emerald-700 dark:text-emerald-300 hover:bg-emerald-50 dark:hover:bg-emerald-950/30">
            <RefreshCw className="size-4" />
            ลองใหม่อีกครั้ง
          </Button>
        </CardContent>
      </Card>
    );
  }

  const summaryCards = [
    { label: 'พนักงานทั้งหมด', value: stats.totalEmployees, icon: Users, color: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-100 dark:bg-emerald-900/40' },
    { label: 'ผู้ลงคะแนน', value: stats.totalVoters, icon: UserCheck, color: 'text-teal-600 dark:text-teal-400', bg: 'bg-teal-100 dark:bg-teal-900/40' },
    { label: 'ผู้สมัคร', value: stats.totalCandidates, icon: UserPlus, color: 'text-amber-600 dark:text-amber-400', bg: 'bg-amber-100 dark:bg-amber-900/40' },
    { label: 'คะแนนทั้งหมด', value: stats.totalVotes, icon: Vote, color: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-100 dark:bg-emerald-900/40' },
    { label: 'อัตราการมีส่วนร่วม', value: `${stats.overallParticipation}%`, icon: BarChart3, color: 'text-teal-600 dark:text-teal-400', bg: 'bg-teal-100 dark:bg-teal-900/40' },
  ];

  return (
    <div className="space-y-6">
      {/* Summary Cards */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
        {summaryCards.map((card) => (
          <Card key={card.label} className="py-4">
            <CardContent className="p-4 pt-0">
              <div className="flex items-center gap-3">
                <div className={`shrink-0 w-10 h-10 rounded-lg ${card.bg} flex items-center justify-center`}>
                  <card.icon className={`size-5 ${card.color}`} />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground truncate">{card.label}</p>
                  <p className={`text-lg font-bold ${card.color}`}>
                    {card.value}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Overall Progress */}
      <Card className="border-emerald-200 dark:border-emerald-800/50">
        <CardHeader className="pb-2">
          <CardTitle className="text-base flex items-center gap-2">
            <BarChart3 className="size-5 text-emerald-600 dark:text-emerald-400" />
            อัตราการมีส่วนร่วมโดยรวม
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-4">
            <Progress
              value={stats.overallParticipation}
              className="flex-1 h-3 bg-emerald-100 dark:bg-emerald-950/40 [&>[data-slot=progress-indicator]]:bg-emerald-500"
            />
            <span className="text-sm font-bold text-emerald-700 dark:text-emerald-300 min-w-[3rem] text-right">
              {stats.overallParticipation}%
            </span>
          </div>
          <p className="text-xs text-muted-foreground mt-2">
            {stats.totalVoters} จาก {stats.totalEmployees} พนักงานได้ลงคะแนนแล้ว
          </p>
        </CardContent>
      </Card>

      {/* Per-Branch Stats Table */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <Building2 className="size-5 text-emerald-600 dark:text-emerald-400" />
            สถิติตามสาขา
          </CardTitle>
          <CardDescription>รายละเอียดการลงคะแนนแยกตามสาขา</CardDescription>
        </CardHeader>
        <CardContent>
          {stats.votesByBranch.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              <Building2 className="size-12 mx-auto mb-3 opacity-40" />
              <p>ยังไม่มีข้อมูลสาขา</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>สาขา</TableHead>
                    <TableHead className="text-right">ผู้มีสิทธิ์</TableHead>
                    <TableHead className="text-right">ผู้ลงคะแนน</TableHead>
                    <TableHead className="text-right">คะแนนทั้งหมด</TableHead>
                    <TableHead className="min-w-[180px]">อัตราการมีส่วนร่วม</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {stats.votesByBranch.map((branch) => (
                    <TableRow key={branch.branchId}>
                      <TableCell>
                        <div className="font-medium">{branch.branchName}</div>
                        <div className="text-xs text-muted-foreground">{branch.branchCode}</div>
                      </TableCell>
                      <TableCell className="text-right">{branch.totalEligibleVoters}</TableCell>
                      <TableCell className="text-right">{branch.totalVoters}</TableCell>
                      <TableCell className="text-right font-medium">{branch.totalVotes}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Progress
                            value={branch.participationRate}
                            className="flex-1 h-2 bg-emerald-100 dark:bg-emerald-950/40 [&>[data-slot=progress-indicator]]:bg-emerald-500"
                          />
                          <span className="text-xs font-medium text-emerald-700 dark:text-emerald-300 min-w-[2.5rem] text-right">
                            {branch.participationRate}%
                          </span>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Refresh Button */}
      <div className="flex justify-end">
        <Button
          onClick={fetchStats}
          variant="outline"
          size="sm"
          className="border-emerald-300 dark:border-emerald-700 text-emerald-700 dark:text-emerald-300 hover:bg-emerald-50 dark:hover:bg-emerald-950/30"
        >
          <RefreshCw className="size-4" />
          รีเฟรชข้อมูล
        </Button>
      </div>
    </div>
  );
}

// ==================== Tab 2: สาขา (Branches) ====================
function BranchesTab() {
  const [branches, setBranches] = useState<Branch[]>([]);
  const [loading, setLoading] = useState(true);
  const [addOpen, setAddOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Branch | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const form = useForm<BranchFormValues>({
    resolver: zodResolver(branchSchema),
    defaultValues: { name: '', code: '' },
  });

  const fetchBranches = useCallback(async () => {
    try {
      setLoading(true);
      const data = await apiFetch<{ success: boolean; branches: Branch[] }>('/api/admin/branches');
      setBranches(data.branches);
    } catch (err) {
      toast.error('ไม่สามารถโหลดข้อมูลสาขาได้', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleAdd = async (values: BranchFormValues) => {
    try {
      setSubmitting(true);
      await apiFetch('/api/admin/branches', {
        method: 'POST',
        body: JSON.stringify(values),
      });
      toast.success('เพิ่มสาขาสำเร็จ', { description: `เพิ่มสาขา "${values.name}" เรียบร้อยแล้ว` });
      setAddOpen(false);
      form.reset();
      fetchBranches();
    } catch (err) {
      toast.error('เพิ่มสาขาไม่สำเร็จ', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      setSubmitting(true);
      await apiFetch('/api/admin/branches', {
        method: 'DELETE',
        body: JSON.stringify({ id: deleteTarget.id }),
      });
      toast.success('ลบสาขาสำเร็จ', { description: `ลบสาขา "${deleteTarget.name}" เรียบร้อยแล้ว` });
      setDeleteTarget(null);
      fetchBranches();
    } catch (err) {
      toast.error('ลบสาขาไม่สำเร็จ', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) return <TableSkeleton />;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">รายการสาขา</h3>
          <p className="text-sm text-muted-foreground">จัดการสาขาขององค์กร</p>
        </div>
        <Button
          onClick={() => setAddOpen(true)}
          className="bg-emerald-600 hover:bg-emerald-700 text-white"
        >
          <Plus className="size-4" />
          เพิ่มสาขา
        </Button>
      </div>

      {/* Branches Table */}
      <Card>
        <CardContent className="p-0">
          {branches.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              <Building2 className="size-12 mx-auto mb-3 opacity-40" />
              <p>ยังไม่มีข้อมูลสาขา</p>
              <p className="text-sm mt-1">กดปุ่ม &quot;เพิ่มสาขา&quot; เพื่อเพิ่มสาขาใหม่</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>ชื่อสาขา</TableHead>
                    <TableHead>รหัส</TableHead>
                    <TableHead className="text-right">จำนวนพนักงาน</TableHead>
                    <TableHead className="text-right">จัดการ</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {branches.map((branch) => (
                    <TableRow key={branch.id}>
                      <TableCell className="font-medium">{branch.name}</TableCell>
                      <TableCell>
                        <Badge variant="secondary" className="bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800">
                          {branch.code}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">{branch.employeeCount ?? 0}</TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => setDeleteTarget(branch)}
                          className="text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950/30"
                        >
                          <Trash2 className="size-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Add Branch Dialog */}
      <Dialog open={addOpen} onOpenChange={setAddOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Plus className="size-5 text-emerald-600 dark:text-emerald-400" />
              เพิ่มสาขาใหม่
            </DialogTitle>
            <DialogDescription>กรอกข้อมูลสาขาที่ต้องการเพิ่ม</DialogDescription>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(handleAdd)} className="space-y-4">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>ชื่อสาขา</FormLabel>
                    <FormControl>
                      <Input placeholder="เช่น สาขากรุงเทพฯ" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="code"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>รหัสสาขา</FormLabel>
                    <FormControl>
                      <Input placeholder="เช่น BKK" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => { setAddOpen(false); form.reset(); }}>
                  ยกเลิก
                </Button>
                <Button type="submit" disabled={submitting} className="bg-emerald-600 hover:bg-emerald-700 text-white">
                  {submitting ? <Loader2 className="size-4 animate-spin" /> : <Plus className="size-4" />}
                  เพิ่มสาขา
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* Delete Branch Confirmation */}
      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <div className="flex items-center gap-3 mb-2">
              <div className="w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/40 flex items-center justify-center shrink-0">
                <Trash2 className="size-5 text-red-600 dark:text-red-400" />
              </div>
              <AlertDialogTitle>ยืนยันการลบสาขา</AlertDialogTitle>
            </div>
            <AlertDialogDescription>
              คุณต้องการลบสาขา <span className="font-semibold text-foreground">&quot;{deleteTarget?.name}&quot;</span> หรือไม่?
              <br />
              <span className="text-red-600 dark:text-red-400 font-medium">การดำเนินการนี้ไม่สามารถย้อนกลับได้</span>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={submitting}>ยกเลิก</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={submitting}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              {submitting ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
              ลบสาขา
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

// ==================== Tab 3: พนักงาน (Employees) ====================
function EmployeesTab() {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [branches, setBranches] = useState<Branch[]>([]);
  const [loading, setLoading] = useState(true);
  const [addOpen, setAddOpen] = useState(false);
  const [editTarget, setEditTarget] = useState<Employee | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Employee | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [search, setSearch] = useState('');

  const addForm = useForm<EmployeeFormValues>({
    resolver: zodResolver(employeeSchema),
    defaultValues: { employeeId: '', name: '', branchId: '', pin: '', isAdmin: false },
  });

  const editForm = useForm<EmployeeEditFormValues>({
    resolver: zodResolver(employeeEditSchema),
    defaultValues: { name: '', branchId: '', pin: '', isAdmin: false, isActive: true },
  });

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      const [empData, branchData] = await Promise.all([
        apiFetch<{ success: boolean; employees: Employee[] }>('/api/admin/employees'),
        apiFetch<{ success: boolean; branches: Branch[] }>('/api/admin/branches'),
      ]);
      setEmployees(empData.employees);
      setBranches(branchData.branches);
    } catch (err) {
      toast.error('ไม่สามารถโหลดข้อมูลพนักงานได้', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleAdd = async (values: EmployeeFormValues) => {
    try {
      setSubmitting(true);
      await apiFetch('/api/admin/employees', {
        method: 'POST',
        body: JSON.stringify(values),
      });
      toast.success('เพิ่มพนักงานสำเร็จ', { description: `เพิ่ม "${values.name}" เรียบร้อยแล้ว` });
      setAddOpen(false);
      addForm.reset();
      fetchData();
    } catch (err) {
      toast.error('เพิ่มพนักงานไม่สำเร็จ', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handleEdit = async (values: EmployeeEditFormValues) => {
    if (!editTarget) return;
    try {
      setSubmitting(true);
      const body: Record<string, unknown> = {
        id: editTarget.id,
        name: values.name,
        branchId: values.branchId,
        isAdmin: values.isAdmin,
        isActive: values.isActive,
      };
      if (values.pin && values.pin.length > 0) {
        body.pin = values.pin;
      }
      await apiFetch('/api/admin/employees', {
        method: 'PUT',
        body: JSON.stringify(body),
      });
      toast.success('แก้ไขพนักงานสำเร็จ', { description: `แก้ไข "${values.name}" เรียบร้อยแล้ว` });
      setEditTarget(null);
      editForm.reset();
      fetchData();
    } catch (err) {
      toast.error('แก้ไขพนักงานไม่สำเร็จ', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeactivate = async () => {
    if (!deleteTarget) return;
    try {
      setSubmitting(true);
      await apiFetch('/api/admin/employees', {
        method: 'DELETE',
        body: JSON.stringify({ id: deleteTarget.id }),
      });
      toast.success('ปิดใช้งานพนักงานสำเร็จ', { description: `ปิดใช้งาน "${deleteTarget.name}" เรียบร้อยแล้ว` });
      setDeleteTarget(null);
      fetchData();
    } catch (err) {
      toast.error('ปิดใช้งานพนักงานไม่สำเร็จ', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setSubmitting(false);
    }
  };

  const openEdit = (emp: Employee) => {
    setEditTarget(emp);
    editForm.reset({
      name: emp.name,
      branchId: emp.branchId,
      pin: '',
      isAdmin: emp.isAdmin,
      isActive: emp.isActive,
    });
  };

  // Filter employees
  const filteredEmployees = employees.filter((emp) => {
    const q = search.toLowerCase();
    return (
      emp.name.toLowerCase().includes(q) ||
      emp.employeeId.toLowerCase().includes(q) ||
      emp.branchName.toLowerCase().includes(q) ||
      emp.branchCode.toLowerCase().includes(q)
    );
  });

  if (loading) return <TableSkeleton rows={8} />;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
        <div>
          <h3 className="text-lg font-semibold">รายการพนักงาน</h3>
          <p className="text-sm text-muted-foreground">จัดการพนักงานในระบบ ({employees.length} คน)</p>
        </div>
        <Button
          onClick={() => setAddOpen(true)}
          className="bg-emerald-600 hover:bg-emerald-700 text-white"
        >
          <Plus className="size-4" />
          เพิ่มพนักงาน
        </Button>
      </div>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
        <Input
          placeholder="ค้นหาพนักงาน... (ชื่อ, รหัส, สาขา)"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-10"
        />
      </div>

      {/* Employees Table */}
      <Card>
        <CardContent className="p-0">
          {filteredEmployees.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              <Users className="size-12 mx-auto mb-3 opacity-40" />
              <p>{search ? 'ไม่พบพนักงานที่ค้นหา' : 'ยังไม่มีข้อมูลพนักงาน'}</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>รหัสพนักงาน</TableHead>
                    <TableHead>ชื่อ</TableHead>
                    <TableHead>สาขา</TableHead>
                    <TableHead className="text-center">แอดมิน</TableHead>
                    <TableHead className="text-center">สถานะ</TableHead>
                    <TableHead className="text-right">จัดการ</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredEmployees.map((emp) => (
                    <TableRow key={emp.id} className={!emp.isActive ? 'opacity-50' : ''}>
                      <TableCell className="font-mono text-sm">{emp.employeeId}</TableCell>
                      <TableCell className="font-medium">{emp.name}</TableCell>
                      <TableCell>
                        <Badge variant="secondary" className="bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800">
                          {emp.branchName}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-center">
                        {emp.isAdmin ? (
                          <Badge className="bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800">
                            <Shield className="size-3" />
                            แอดมิน
                          </Badge>
                        ) : (
                          <span className="text-muted-foreground text-sm">—</span>
                        )}
                      </TableCell>
                      <TableCell className="text-center">
                        {emp.isActive ? (
                          <Badge className="bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800">
                            <CheckCircle2 className="size-3" />
                            ใช้งาน
                          </Badge>
                        ) : (
                          <Badge variant="destructive" className="bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300 border-red-200 dark:border-red-800">
                            <XCircle className="size-3" />
                            ปิดใช้งาน
                          </Badge>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end gap-1">
                          <Button variant="ghost" size="sm" onClick={() => openEdit(emp)} className="text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50 dark:hover:bg-emerald-950/30">
                            <Pencil className="size-4" />
                          </Button>
                          {emp.isActive && (
                            <Button variant="ghost" size="sm" onClick={() => setDeleteTarget(emp)} className="text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950/30">
                              <XCircle className="size-4" />
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Add Employee Dialog */}
      <Dialog open={addOpen} onOpenChange={setAddOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <UserPlus className="size-5 text-emerald-600 dark:text-emerald-400" />
              เพิ่มพนักงานใหม่
            </DialogTitle>
            <DialogDescription>กรอกข้อมูลพนักงานที่ต้องการเพิ่ม</DialogDescription>
          </DialogHeader>
          <Form {...addForm}>
            <form onSubmit={addForm.handleSubmit(handleAdd)} className="space-y-4">
              <FormField
                control={addForm.control}
                name="employeeId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>รหัสพนักงาน</FormLabel>
                    <FormControl>
                      <Input placeholder="เช่น EMP001" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={addForm.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>ชื่อ-นามสกุล</FormLabel>
                    <FormControl>
                      <Input placeholder="เช่น สมชาย ใจดี" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={addForm.control}
                name="branchId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>สาขา</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger className="w-full">
                          <SelectValue placeholder="เลือกสาขา" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {branches.map((branch) => (
                          <SelectItem key={branch.id} value={branch.id}>
                            {branch.name} ({branch.code})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={addForm.control}
                name="pin"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>PIN</FormLabel>
                    <FormControl>
                      <Input type="password" placeholder="รหัส PIN อย่างน้อย 4 ตัว" {...field} />
                    </FormControl>
                    <FormDescription>ใช้สำหรับเข้าสู่ระบบ</FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={addForm.control}
                name="isAdmin"
                render={({ field }) => (
                  <FormItem className="flex items-center justify-between rounded-lg border p-3">
                    <div className="space-y-0.5">
                      <FormLabel className="flex items-center gap-2">
                        <Shield className="size-4 text-amber-600 dark:text-amber-400" />
                        สิทธิ์แอดมิน
                      </FormLabel>
                      <FormDescription>ให้สิทธิ์จัดการระบบแก่พนักงาน</FormDescription>
                    </div>
                    <FormControl>
                      <Switch checked={field.value} onCheckedChange={field.onChange} />
                    </FormControl>
                  </FormItem>
                )}
              />
              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => { setAddOpen(false); addForm.reset(); }}>
                  ยกเลิก
                </Button>
                <Button type="submit" disabled={submitting} className="bg-emerald-600 hover:bg-emerald-700 text-white">
                  {submitting ? <Loader2 className="size-4 animate-spin" /> : <Plus className="size-4" />}
                  เพิ่มพนักงาน
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* Edit Employee Dialog */}
      <Dialog open={!!editTarget} onOpenChange={(open) => { if (!open) { setEditTarget(null); editForm.reset(); } }}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Pencil className="size-5 text-emerald-600 dark:text-emerald-400" />
              แก้ไขพนักงาน
            </DialogTitle>
            <DialogDescription>แก้ไขข้อมูลพนักงาน {editTarget?.name}</DialogDescription>
          </DialogHeader>
          <Form {...editForm}>
            <form onSubmit={editForm.handleSubmit(handleEdit)} className="space-y-4">
              <FormField
                control={editForm.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>ชื่อ-นามสกุล</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={editForm.control}
                name="branchId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>สาขา</FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger className="w-full">
                          <SelectValue placeholder="เลือกสาขา" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {branches.map((branch) => (
                          <SelectItem key={branch.id} value={branch.id}>
                            {branch.name} ({branch.code})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={editForm.control}
                name="pin"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>PIN ใหม่ (ไม่ต้องกรอกหากไม่ต้องการเปลี่ยน)</FormLabel>
                    <FormControl>
                      <Input type="password" placeholder="เว้นว่างไว้หากไม่ต้องการเปลี่ยน PIN" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={editForm.control}
                name="isAdmin"
                render={({ field }) => (
                  <FormItem className="flex items-center justify-between rounded-lg border p-3">
                    <div className="space-y-0.5">
                      <FormLabel className="flex items-center gap-2">
                        <Shield className="size-4 text-amber-600 dark:text-amber-400" />
                        สิทธิ์แอดมิน
                      </FormLabel>
                    </div>
                    <FormControl>
                      <Switch checked={field.value} onCheckedChange={field.onChange} />
                    </FormControl>
                  </FormItem>
                )}
              />
              <FormField
                control={editForm.control}
                name="isActive"
                render={({ field }) => (
                  <FormItem className="flex items-center justify-between rounded-lg border p-3">
                    <div className="space-y-0.5">
                      <FormLabel className="flex items-center gap-2">
                        <UserCheck className="size-4 text-emerald-600 dark:text-emerald-400" />
                        ใช้งานอยู่
                      </FormLabel>
                    </div>
                    <FormControl>
                      <Switch checked={field.value} onCheckedChange={field.onChange} />
                    </FormControl>
                  </FormItem>
                )}
              />
              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => { setEditTarget(null); editForm.reset(); }}>
                  ยกเลิก
                </Button>
                <Button type="submit" disabled={submitting} className="bg-emerald-600 hover:bg-emerald-700 text-white">
                  {submitting ? <Loader2 className="size-4 animate-spin" /> : <Pencil className="size-4" />}
                  บันทึกการแก้ไข
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* Deactivate Employee Confirmation */}
      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <div className="flex items-center gap-3 mb-2">
              <div className="w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/40 flex items-center justify-center shrink-0">
                <XCircle className="size-5 text-red-600 dark:text-red-400" />
              </div>
              <AlertDialogTitle>ยืนยันการปิดใช้งาน</AlertDialogTitle>
            </div>
            <AlertDialogDescription>
              คุณต้องการปิดใช้งานพนักงาน <span className="font-semibold text-foreground">&quot;{deleteTarget?.name}&quot;</span> หรือไม่?
              <br />
              พนักงานที่ปิดใช้งานจะไม่สามารถเข้าสู่ระบบได้
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={submitting}>ยกเลิก</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDeactivate}
              disabled={submitting}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              {submitting ? <Loader2 className="size-4 animate-spin" /> : <XCircle className="size-4" />}
              ปิดใช้งาน
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

// ==================== Tab 4: ผู้สมัคร (Candidates) ====================
function CandidatesTab() {
  const [candidates, setCandidates] = useState<Candidate[]>([]);
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [loading, setLoading] = useState(true);
  const [addOpen, setAddOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Candidate | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [selectedEmployeeId, setSelectedEmployeeId] = useState('');

  const form = useForm<CandidateFormValues>({
    resolver: zodResolver(candidateSchema),
    defaultValues: { employeeId: '', branchId: '' },
  });

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      const [candData, empData] = await Promise.all([
        apiFetch<{ success: boolean; candidates: Candidate[] }>('/api/admin/candidates'),
        apiFetch<{ success: boolean; employees: Employee[] }>('/api/admin/employees'),
      ]);
      setCandidates(candData.candidates);
      setEmployees(empData.employees);
    } catch (err) {
      toast.error('ไม่สามารถโหลดข้อมูลผู้สมัครได้', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setLoading(false);
    }
  }, []);

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

  // Employees who are not yet candidates (and are active)
  const candidateEmployeeIds = new Set(candidates.map((c) => c.employeeId));
  const availableEmployees = employees.filter(
    (emp) => emp.isActive && !candidateEmployeeIds.has(emp.id)
  );

  // Auto-fill branch when employee is selected
  const handleEmployeeSelect = (empId: string) => {
    setSelectedEmployeeId(empId);
    form.setValue('employeeId', empId);
    const emp = employees.find((e) => e.id === empId);
    if (emp) {
      form.setValue('branchId', emp.branchId);
    }
  };

  const handleAdd = async (values: CandidateFormValues) => {
    try {
      setSubmitting(true);
      await apiFetch('/api/admin/candidates', {
        method: 'POST',
        body: JSON.stringify(values),
      });
      const emp = employees.find((e) => e.id === values.employeeId);
      toast.success('เพิ่มผู้สมัครสำเร็จ', { description: `เพิ่ม "${emp?.name}" เป็นผู้สมัครเรียบร้อยแล้ว` });
      setAddOpen(false);
      form.reset();
      setSelectedEmployeeId('');
      fetchData();
    } catch (err) {
      toast.error('เพิ่มผู้สมัครไม่สำเร็จ', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      setSubmitting(true);
      await apiFetch('/api/admin/candidates', {
        method: 'DELETE',
        body: JSON.stringify({ id: deleteTarget.id }),
      });
      toast.success('ลบผู้สมัครสำเร็จ', { description: `ลบ "${deleteTarget.name}" ออกจากรายชื่อผู้สมัครเรียบร้อยแล้ว` });
      setDeleteTarget(null);
      fetchData();
    } catch (err) {
      toast.error('ลบผู้สมัครไม่สำเร็จ', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) return <TableSkeleton rows={6} />;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">รายชื่อผู้สมัคร</h3>
          <p className="text-sm text-muted-foreground">จัดการรายชื่อผู้สมัครรับเลือกตั้ง ({candidates.length} คน)</p>
        </div>
        <Button
          onClick={() => setAddOpen(true)}
          className="bg-emerald-600 hover:bg-emerald-700 text-white"
          disabled={availableEmployees.length === 0}
        >
          <Plus className="size-4" />
          เพิ่มผู้สมัคร
        </Button>
      </div>

      {availableEmployees.length === 0 && candidates.length === 0 && (
        <Card className="border-amber-200 dark:border-amber-800/50 bg-amber-50/30 dark:bg-amber-950/10">
          <CardContent className="p-4 flex items-center gap-3">
            <Users className="size-5 text-amber-600 dark:text-amber-400 shrink-0" />
            <p className="text-sm text-amber-700 dark:text-amber-300">
              ไม่มีพนักงานที่สามารถเพิ่มเป็นผู้สมัครได้ กรุณาเพิ่มพนักงานก่อน
            </p>
          </CardContent>
        </Card>
      )}

      {/* Candidates Table */}
      <Card>
        <CardContent className="p-0">
          {candidates.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              <UsersRound className="size-12 mx-auto mb-3 opacity-40" />
              <p>ยังไม่มีรายชื่อผู้สมัคร</p>
              <p className="text-sm mt-1">กดปุ่ม &quot;เพิ่มผู้สมัคร&quot; เพื่อเพิ่มผู้สมัครใหม่</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>ชื่อผู้สมัคร</TableHead>
                    <TableHead>รหัสพนักงาน</TableHead>
                    <TableHead>สาขา</TableHead>
                    <TableHead>ตำแหน่ง</TableHead>
                    <TableHead className="text-center">สถานะ</TableHead>
                    <TableHead className="text-right">จัดการ</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {candidates.map((cand) => (
                    <TableRow key={cand.id}>
                      <TableCell className="font-medium">{cand.name}</TableCell>
                      <TableCell className="font-mono text-sm">{cand.employeeCode}</TableCell>
                      <TableCell>
                        <Badge variant="secondary" className="bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800">
                          {cand.branchName}
                        </Badge>
                      </TableCell>
                      <TableCell>{cand.position || <span className="text-muted-foreground">—</span>}</TableCell>
                      <TableCell className="text-center">
                        {cand.isApproved ? (
                          <Badge className="bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800">
                            <CheckCircle2 className="size-3" />
                            อนุมัติ
                          </Badge>
                        ) : (
                          <Badge className="bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800">
                            <Clock className="size-3" />
                            รออนุมัติ
                          </Badge>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        <Button variant="ghost" size="sm" onClick={() => setDeleteTarget(cand)} className="text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950/30">
                          <Trash2 className="size-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Add Candidate Dialog */}
      <Dialog open={addOpen} onOpenChange={(open) => { if (!open) { setAddOpen(false); form.reset(); setSelectedEmployeeId(''); } }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <UserPlus className="size-5 text-emerald-600 dark:text-emerald-400" />
              เพิ่มผู้สมัคร
            </DialogTitle>
            <DialogDescription>เลือกพนักงานที่ต้องการเพิ่มเป็นผู้สมัคร</DialogDescription>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(handleAdd)} className="space-y-4">
              <FormField
                control={form.control}
                name="employeeId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>เลือกพนักงาน</FormLabel>
                    <Select onValueChange={handleEmployeeSelect} value={selectedEmployeeId}>
                      <FormControl>
                        <SelectTrigger className="w-full">
                          <SelectValue placeholder="เลือกพนักงานที่ต้องการเพิ่มเป็นผู้สมัคร" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {availableEmployees.length === 0 ? (
                          <SelectItem value="_none" disabled>ไม่มีพนักงานที่สามารถเพิ่มได้</SelectItem>
                        ) : (
                          availableEmployees.map((emp) => (
                            <SelectItem key={emp.id} value={emp.id}>
                              {emp.name} ({emp.employeeId}) — {emp.branchName}
                            </SelectItem>
                          ))
                        )}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              {selectedEmployeeId && (
                <div className="rounded-lg border bg-muted/50 p-3 space-y-1">
                  <p className="text-xs text-muted-foreground">สาขาจะถูกกรอกอัตโนมัติตามสาขาของพนักงาน</p>
                  <p className="text-sm font-medium">
                    สาขา: {employees.find((e) => e.id === selectedEmployeeId)?.branchName || '—'}
                  </p>
                </div>
              )}
              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => { setAddOpen(false); form.reset(); setSelectedEmployeeId(''); }}>
                  ยกเลิก
                </Button>
                <Button type="submit" disabled={submitting || !selectedEmployeeId} className="bg-emerald-600 hover:bg-emerald-700 text-white">
                  {submitting ? <Loader2 className="size-4 animate-spin" /> : <Plus className="size-4" />}
                  เพิ่มผู้สมัคร
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* Delete Candidate Confirmation */}
      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <div className="flex items-center gap-3 mb-2">
              <div className="w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/40 flex items-center justify-center shrink-0">
                <Trash2 className="size-5 text-red-600 dark:text-red-400" />
              </div>
              <AlertDialogTitle>ยืนยันการลบผู้สมัคร</AlertDialogTitle>
            </div>
            <AlertDialogDescription>
              คุณต้องการลบผู้สมัคร <span className="font-semibold text-foreground">&quot;{deleteTarget?.name}&quot;</span> หรือไม่?
              <br />
              <span className="text-red-600 dark:text-red-400 font-medium">
                คะแนนที่เกี่ยวข้องกับผู้สมัครนี้จะถูกลบด้วย
              </span>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={submitting}>ยกเลิก</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={submitting}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              {submitting ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
              ลบผู้สมัคร
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

// ==================== Tab 5: ตั้งค่า (Settings) ====================
function SettingsTab() {
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  const form = useForm<SettingsFormValues>({
    resolver: zodResolver(settingsSchema),
    defaultValues: {
      maxVotesPerPerson: '3',
      votingStartDate: '',
      votingEndDate: '',
      votingEnabled: false,
      resultsVisible: false,
      systemName: 'ระบบการเลือกตั้ง',
    },
  });

  const fetchSettings = useCallback(async () => {
    try {
      setLoading(true);
      const data = await apiFetch<{ success: boolean; settings: AppSettings }>('/api/admin/settings');
      const s = data.settings;
      form.reset({
        maxVotesPerPerson: s.maxVotesPerPerson || '3',
        votingStartDate: formatDateTimeLocal(s.votingStartDate || ''),
        votingEndDate: formatDateTimeLocal(s.votingEndDate || ''),
        votingEnabled: s.votingEnabled === 'true',
        resultsVisible: s.resultsVisible === 'true',
        systemName: s.systemName || 'ระบบการเลือกตั้ง',
      });
    } catch (err) {
      toast.error('ไม่สามารถโหลดการตั้งค่าได้', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setLoading(false);
    }
  }, [form]);

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

  const handleSave = async (values: SettingsFormValues) => {
    try {
      setSubmitting(true);
      await apiFetch('/api/admin/settings', {
        method: 'PUT',
        body: JSON.stringify({
          settings: {
            maxVotesPerPerson: values.maxVotesPerPerson,
            votingStartDate: values.votingStartDate ? new Date(values.votingStartDate).toISOString() : '',
            votingEndDate: values.votingEndDate ? new Date(values.votingEndDate).toISOString() : '',
            votingEnabled: String(values.votingEnabled),
            resultsVisible: String(values.resultsVisible),
            systemName: values.systemName,
          },
        }),
      });
      toast.success('บันทึกการตั้งค่าสำเร็จ');
    } catch (err) {
      toast.error('บันทึกการตั้งค่าไม่สำเร็จ', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="space-y-6 max-w-2xl">
        <Skeleton className="h-8 w-48" />
        {Array.from({ length: 6 }).map((_, i) => (
          <Skeleton key={i} className="h-16 w-full rounded-lg" />
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-2xl">
      <div>
        <h3 className="text-lg font-semibold">ตั้งค่าระบบ</h3>
        <p className="text-sm text-muted-foreground">กำหนดค่าต่างๆ ของระบบการเลือกตั้ง</p>
      </div>

      <Form {...form}>
        <form onSubmit={form.handleSubmit(handleSave)} className="space-y-6">
          {/* System Name */}
          <FormField
            control={form.control}
            name="systemName"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="flex items-center gap-2">
                  <Type className="size-4 text-emerald-600 dark:text-emerald-400" />
                  ชื่อระบบ
                </FormLabel>
                <FormControl>
                  <Input {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <Separator />

          {/* Max Votes Per Person */}
          <FormField
            control={form.control}
            name="maxVotesPerPerson"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="flex items-center gap-2">
                  <Hash className="size-4 text-emerald-600 dark:text-emerald-400" />
                  จำนวนคะแนนสูงสุดต่อคน
                </FormLabel>
                <FormControl>
                  <Input type="number" min="1" max="100" {...field} />
                </FormControl>
                <FormDescription>จำนวนผู้สมัครที่พนักงานสามารถเลือกได้สูงสุด</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          <Separator />

          {/* Voting Period */}
          <div className="space-y-4">
            <h4 className="text-sm font-medium flex items-center gap-2">
              <Clock className="size-4 text-amber-600 dark:text-amber-400" />
              ช่วงเวลาการเลือกตั้ง
            </h4>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="votingStartDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>วันเริ่มต้น</FormLabel>
                    <FormControl>
                      <Input type="datetime-local" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="votingEndDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>วันสิ้นสุด</FormLabel>
                    <FormControl>
                      <Input type="datetime-local" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>

          <Separator />

          {/* Toggles */}
          <div className="space-y-4">
            <h4 className="text-sm font-medium flex items-center gap-2">
              <ToggleLeft className="size-4 text-emerald-600 dark:text-emerald-400" />
              สวิตช์ควบคุม
            </h4>

            <FormField
              control={form.control}
              name="votingEnabled"
              render={({ field }) => (
                <FormItem className="flex items-center justify-between rounded-lg border p-4">
                  <div className="space-y-0.5">
                    <FormLabel className="flex items-center gap-2">
                      <Vote className="size-4 text-emerald-600 dark:text-emerald-400" />
                      เปิดการลงคะแนน
                    </FormLabel>
                    <FormDescription>เปิด/ปิด ระบบการลงคะแนนชั่วคราว</FormDescription>
                  </div>
                  <FormControl>
                    <Switch checked={field.value} onCheckedChange={field.onChange} />
                  </FormControl>
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="resultsVisible"
              render={({ field }) => (
                <FormItem className="flex items-center justify-between rounded-lg border p-4">
                  <div className="space-y-0.5">
                    <FormLabel className="flex items-center gap-2">
                      <Eye className="size-4 text-amber-600 dark:text-amber-400" />
                      แสดงผลคะแนน
                    </FormLabel>
                    <FormDescription>อนุญาตให้พนักงานดูผลคะแนนได้</FormDescription>
                  </div>
                  <FormControl>
                    <Switch checked={field.value} onCheckedChange={field.onChange} />
                  </FormControl>
                </FormItem>
              )}
            />
          </div>

          <Separator />

          {/* Save Button */}
          <div className="flex justify-end">
            <Button type="submit" disabled={submitting} className="bg-emerald-600 hover:bg-emerald-700 text-white min-w-[140px]">
              {submitting ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  กำลังบันทึก...
                </>
              ) : (
                'บันทึกการตั้งค่า'
              )}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}

// ==================== Main Admin Dashboard Component ====================
export default function AdminDashboard() {
  return (
    <div className="w-full max-w-6xl mx-auto p-4 sm:p-6 space-y-6">
      {/* Header */}
      <div className="text-center space-y-2">
        <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-800">
          <Shield className="size-5 text-emerald-600 dark:text-emerald-400" />
          <span className="font-semibold text-emerald-700 dark:text-emerald-300">
            แผงควบคุมผู้ดูแลระบบ
          </span>
        </div>
        <h1 className="text-2xl sm:text-3xl font-bold text-foreground">
          จัดการระบบการเลือกตั้ง
        </h1>
        <p className="text-muted-foreground text-sm">
          จัดการสาขา พนักงาน ผู้สมัคร และตั้งค่าระบบ
        </p>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="stats" className="space-y-6">
        <TabsList className="w-full sm:w-auto flex flex-wrap h-auto gap-1 bg-muted/50 p-1">
          <TabsTrigger value="stats" className="flex items-center gap-1.5 data-[state=active]:bg-emerald-50 data-[state=active]:text-emerald-700 dark:data-[state=active]:bg-emerald-950/30 dark:data-[state=active]:text-emerald-300">
            <BarChart3 className="size-4" />
            <span className="hidden sm:inline">สถิติ</span>
            <span className="sm:hidden">สถิติ</span>
          </TabsTrigger>
          <TabsTrigger value="branches" className="flex items-center gap-1.5 data-[state=active]:bg-emerald-50 data-[state=active]:text-emerald-700 dark:data-[state=active]:bg-emerald-950/30 dark:data-[state=active]:text-emerald-300">
            <Building2 className="size-4" />
            <span className="hidden sm:inline">สาขา</span>
            <span className="sm:hidden">สาขา</span>
          </TabsTrigger>
          <TabsTrigger value="employees" className="flex items-center gap-1.5 data-[state=active]:bg-emerald-50 data-[state=active]:text-emerald-700 dark:data-[state=active]:bg-emerald-950/30 dark:data-[state=active]:text-emerald-300">
            <Users className="size-4" />
            <span className="hidden sm:inline">พนักงาน</span>
            <span className="sm:hidden">พนักงาน</span>
          </TabsTrigger>
          <TabsTrigger value="candidates" className="flex items-center gap-1.5 data-[state=active]:bg-emerald-50 data-[state=active]:text-emerald-700 dark:data-[state=active]:bg-emerald-950/30 dark:data-[state=active]:text-emerald-300">
            <UserPlus className="size-4" />
            <span className="hidden sm:inline">ผู้สมัคร</span>
            <span className="sm:hidden">ผู้สมัคร</span>
          </TabsTrigger>
          <TabsTrigger value="settings" className="flex items-center gap-1.5 data-[state=active]:bg-emerald-50 data-[state=active]:text-emerald-700 dark:data-[state=active]:bg-emerald-950/30 dark:data-[state=active]:text-emerald-300">
            <Settings className="size-4" />
            <span className="hidden sm:inline">ตั้งค่า</span>
            <span className="sm:hidden">ตั้งค่า</span>
          </TabsTrigger>
        </TabsList>

        <TabsContent value="stats">
          <StatsTab />
        </TabsContent>

        <TabsContent value="branches">
          <BranchesTab />
        </TabsContent>

        <TabsContent value="employees">
          <EmployeesTab />
        </TabsContent>

        <TabsContent value="candidates">
          <CandidatesTab />
        </TabsContent>

        <TabsContent value="settings">
          <SettingsTab />
        </TabsContent>
      </Tabs>
    </div>
  );
}
