'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Vote,
  Clock,
  ShieldCheck,
  CheckCircle2,
  AlertTriangle,
  Users,
  Loader2,
  Ban,
  UserCheck,
} from 'lucide-react';
import { toast } from 'sonner';
import { motion, AnimatePresence } from 'framer-motion';

import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Skeleton } from '@/components/ui/skeleton';

// ==================== Types ====================
interface Candidate {
  id: string;
  name: string;
  position: string;
  statement: string;
  photoUrl: string | null;
  employeeId: string;
}

interface Branch {
  id: string;
  name: string;
  code: string;
}

interface VotingStatus {
  canVote: boolean;
  voteCount: number;
  maxVotes: number;
  votingEnabled: boolean;
  votingStartDate: string;
  votingEndDate: string;
  isWithinPeriod: boolean;
  branch: Branch;
  candidates: Candidate[];
}

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

// ==================== Loading Skeleton ====================
function VotingPanelSkeleton() {
  return (
    <div className="w-full max-w-4xl mx-auto p-4 sm:p-6 space-y-6">
      <Skeleton className="h-10 w-48 mx-auto" />
      <Skeleton className="h-6 w-64 mx-auto" />
      <div className="space-y-3">
        <Skeleton className="h-4 w-32" />
        <Skeleton className="h-2 w-full" />
      </div>
      <div className="grid grid-cols-2 lg:grid-cols-3 gap-4">
        {Array.from({ length: 6 }).map((_, i) => (
          <Skeleton key={i} className="h-48 rounded-xl" />
        ))}
      </div>
      <Skeleton className="h-12 w-full" />
    </div>
  );
}

// ==================== Voting Closed State ====================
function VotingClosedState({
  votingEnabled,
  isWithinPeriod,
  votingStartDate,
  votingEndDate,
}: {
  votingEnabled: boolean;
  isWithinPeriod: boolean;
  votingStartDate: string;
  votingEndDate: string;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
      className="flex flex-col items-center justify-center py-12 px-4"
    >
      <div className="w-20 h-20 rounded-full bg-red-50 dark:bg-red-950/30 flex items-center justify-center mb-6">
        <Ban className="size-10 text-red-500" />
      </div>
      <h2 className="text-2xl font-bold text-foreground mb-2">
        การลงคะแนนยังไม่เปิด
      </h2>
      <p className="text-muted-foreground text-center max-w-md mb-6">
        {!votingEnabled
          ? 'ระบบการเลือกตั้งยังไม่เปิดให้ใช้งาน กรุณารอการแจ้งเตือนจากผู้ดูแลระบบ'
          : 'ขณะนี้ไม่อยู่ในช่วงเวลาที่กำหนดการเลือกตั้ง'}
      </p>

      {(votingStartDate || votingEndDate) && (
        <Card className="w-full max-w-sm border-amber-200 dark:border-amber-900/50 bg-amber-50/50 dark:bg-amber-950/20">
          <CardContent className="p-4 space-y-3">
            <div className="flex items-center gap-2 text-amber-700 dark:text-amber-400">
              <Clock className="size-4 shrink-0" />
              <span className="text-sm font-medium">ช่วงเวลาการเลือกตั้ง</span>
            </div>
            {votingStartDate && (
              <div className="flex items-start gap-2 text-sm">
                <span className="text-muted-foreground shrink-0">เริ่ม:</span>
                <span className="font-medium">{formatDate(votingStartDate)}</span>
              </div>
            )}
            {votingEndDate && (
              <div className="flex items-start gap-2 text-sm">
                <span className="text-muted-foreground shrink-0">สิ้นสุด:</span>
                <span className="font-medium">{formatDate(votingEndDate)}</span>
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </motion.div>
  );
}

// ==================== Already Voted State ====================
function AlreadyVotedState({ voteCount, maxVotes }: { voteCount: number; maxVotes: number }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
      className="flex flex-col items-center justify-center py-12 px-4"
    >
      <motion.div
        initial={{ scale: 0 }}
        animate={{ scale: 1 }}
        transition={{ type: 'spring', stiffness: 200, damping: 15, delay: 0.2 }}
        className="w-24 h-24 rounded-full bg-emerald-50 dark:bg-emerald-950/30 flex items-center justify-center mb-6"
      >
        <CheckCircle2 className="size-12 text-emerald-500" />
      </motion.div>
      <h2 className="text-2xl font-bold text-foreground mb-2">
        คุณได้ใช้สิทธิ์ลงคะแนนครบแล้ว
      </h2>
      <p className="text-muted-foreground text-center max-w-md mb-4">
        คุณได้ลงคะแนนไปแล้ว {voteCount} จาก {maxVotes} คะแนน
      </p>
      <Progress
        value={(voteCount / maxVotes) * 100}
        className="w-full max-w-xs h-3 bg-emerald-100 dark:bg-emerald-950/40"
      />
      <p className="text-xs text-muted-foreground mt-3">
        ขอบคุณที่ร่วมลงคะแนน
      </p>
    </motion.div>
  );
}

// ==================== Candidate Card ====================
function CandidateCard({
  candidate,
  isSelected,
  isDisabled,
  onToggle,
}: {
  candidate: Candidate;
  isSelected: boolean;
  isDisabled: boolean;
  onToggle: () => void;
}) {
  return (
    <motion.div
      whileHover={!isDisabled ? { scale: 1.02 } : undefined}
      whileTap={!isDisabled ? { scale: 0.98 } : undefined}
      transition={{ duration: 0.15 }}
    >
      <Card
        className={`relative cursor-pointer transition-all duration-200 overflow-hidden py-0 gap-0 ${
          isSelected
            ? 'border-emerald-500 dark:border-emerald-400 bg-emerald-50/60 dark:bg-emerald-950/20 shadow-emerald-100 dark:shadow-emerald-950/30 shadow-md'
            : isDisabled
            ? 'border-muted bg-muted/30 opacity-60 cursor-not-allowed'
            : 'border-border hover:border-emerald-300 dark:hover:border-emerald-700 hover:shadow-sm'
        }`}
        onClick={!isDisabled ? onToggle : undefined}
      >
        <CardHeader className="p-4 pb-2">
          <div className="flex items-start gap-3">
            <div
              className={`shrink-0 w-12 h-12 rounded-full flex items-center justify-center text-lg font-bold ${
                isSelected
                  ? 'bg-emerald-500 text-white'
                  : isDisabled
                  ? 'bg-muted text-muted-foreground'
                  : 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300'
              }`}
            >
              {candidate.name.charAt(0)}
            </div>
            <div className="flex-1 min-w-0">
              <CardTitle
                className={`text-base leading-tight ${
                  isSelected
                    ? 'text-emerald-700 dark:text-emerald-300'
                    : isDisabled
                    ? 'text-muted-foreground'
                    : 'text-foreground'
                }`}
              >
                {candidate.name}
              </CardTitle>
              {candidate.position && (
                <Badge
                  variant="secondary"
                  className={`mt-1 text-xs ${
                    isSelected
                      ? 'bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800'
                      : ''
                  }`}
                >
                  {candidate.position}
                </Badge>
              )}
            </div>
            <Checkbox
              checked={isSelected}
              disabled={isDisabled}
              className={`${
                isSelected
                  ? 'border-emerald-500 data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500'
                  : ''
              }`}
              onCheckedChange={!isDisabled ? onToggle : undefined}
              onClick={(e) => e.stopPropagation()}
            />
          </div>
        </CardHeader>
        {candidate.statement && (
          <CardContent className="px-4 pb-4 pt-0">
            <p
              className={`text-sm leading-relaxed line-clamp-3 ${
                isDisabled ? 'text-muted-foreground/70' : 'text-muted-foreground'
              }`}
            >
              {candidate.statement}
            </p>
          </CardContent>
        )}
        {isSelected && (
          <div className="absolute top-0 right-0">
            <div className="w-0 h-0 border-t-[2rem] border-t-emerald-500 dark:border-t-emerald-400 border-l-[2rem] border-l-transparent" />
            <CheckCircle2 className="absolute top-1 right-1 size-4 text-white" />
          </div>
        )}
      </Card>
    </motion.div>
  );
}

// ==================== Success State ====================
function VoteSuccessState({ onReset }: { onReset: () => void }) {
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.9 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ duration: 0.5, type: 'spring' }}
      className="flex flex-col items-center justify-center py-16 px-4"
    >
      <motion.div
        initial={{ scale: 0, rotate: -180 }}
        animate={{ scale: 1, rotate: 0 }}
        transition={{ type: 'spring', stiffness: 150, damping: 12, delay: 0.1 }}
        className="relative mb-8"
      >
        <div className="w-28 h-28 rounded-full bg-emerald-100 dark:bg-emerald-950/40 flex items-center justify-center">
          <CheckCircle2 className="size-16 text-emerald-500" />
        </div>
        {/* Decorative circles for confetti-like effect */}
        {[
          { x: -40, y: -30, delay: 0.3, size: 8, color: 'bg-amber-400' },
          { x: 50, y: -20, delay: 0.4, size: 6, color: 'bg-emerald-400' },
          { x: -30, y: 40, delay: 0.5, size: 10, color: 'bg-teal-400' },
          { x: 45, y: 35, delay: 0.35, size: 7, color: 'bg-amber-300' },
          { x: 0, y: -50, delay: 0.45, size: 5, color: 'bg-emerald-300' },
        ].map((dot, i) => (
          <motion.div
            key={i}
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ delay: dot.delay, duration: 0.3 }}
            className={`absolute ${dot.color} rounded-full`}
            style={{
              width: dot.size,
              height: dot.size,
              left: `calc(50% + ${dot.x}px)`,
              top: `calc(50% + ${dot.y}px)`,
            }}
          />
        ))}
      </motion.div>
      <motion.h2
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.4 }}
        className="text-2xl font-bold text-foreground mb-2"
      >
        ลงคะแนนสำเร็จ!
      </motion.h2>
      <motion.p
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.5 }}
        className="text-muted-foreground text-center max-w-md mb-6"
      >
        การลงคะแนนของคุณถูกบันทึกเรียบร้อยแล้ว การลงคะแนนเป็นการไม่เปิดเผยตัวตน
      </motion.p>
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.6 }}
      >
        <Button
          onClick={onReset}
          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"
        >
          กลับหน้าหลัก
        </Button>
      </motion.div>
    </motion.div>
  );
}

// ==================== Main Component ====================
export default function VotingPanel() {
  const [votingStatus, setVotingStatus] = useState<VotingStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [submitting, setSubmitting] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Fetch voting status
  const fetchVotingStatus = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await fetch('/api/vote');
      if (!res.ok) {
        const data = await res.json().catch(() => null);
        throw new Error(data?.error || 'ไม่สามารถโหลดข้อมูลได้');
      }
      const data: VotingStatus = await res.json();
      setVotingStatus(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'เกิดข้อผิดพลาดในระบบ');
      toast.error('ไม่สามารถโหลดข้อมูลได้', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setLoading(false);
    }
  }, []);

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

  // Toggle candidate selection
  const toggleCandidate = useCallback(
    (candidateId: string) => {
      if (!votingStatus) return;

      setSelectedIds((prev) => {
        const next = new Set(prev);
        if (next.has(candidateId)) {
          next.delete(candidateId);
        } else {
          // Check if we can select more
          const remaining = votingStatus.maxVotes - votingStatus.voteCount;
          if (next.size >= remaining) {
            toast.warning('ไม่สามารถเลือกได้มากกว่านี้', {
              description: `คุณสามารถเลือกได้สูงสุด ${remaining} คน`,
            });
            return prev;
          }
          next.add(candidateId);
        }
        return next;
      });
    },
    [votingStatus]
  );

  // Submit vote
  const handleSubmit = useCallback(async () => {
    if (!votingStatus || selectedIds.size === 0) return;

    setSubmitting(true);
    setConfirmOpen(false);
    try {
      const res = await fetch('/api/vote', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ candidateIds: Array.from(selectedIds) }),
      });

      const data = await res.json().catch(() => null);

      if (!res.ok || data?.success === false) {
        throw new Error(data?.error || 'เกิดข้อผิดพลาดในการลงคะแนน');
      }

      toast.success('ลงคะแนนสำเร็จ!', {
        description: `คุณได้ลงคะแนนให้ ${selectedIds.size} ผู้สมัคร`,
      });

      setShowSuccess(true);
      setSelectedIds(new Set());
    } catch (err) {
      toast.error('ลงคะแนนไม่สำเร็จ', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setSubmitting(false);
    }
  }, [votingStatus, selectedIds]);

  // Reset after success
  const handleReset = useCallback(() => {
    setShowSuccess(false);
    fetchVotingStatus();
  }, [fetchVotingStatus]);

  // ==================== Render ====================

  // Loading state
  if (loading) {
    return <VotingPanelSkeleton />;
  }

  // Error state
  if (error || !votingStatus) {
    return (
      <div className="w-full max-w-4xl mx-auto p-4 sm:p-6">
        <Alert variant="destructive">
          <AlertTriangle className="size-4" />
          <AlertTitle>เกิดข้อผิดพลาด</AlertTitle>
          <AlertDescription>
            {error || 'ไม่สามารถโหลดข้อมูลได้ กรุณาลองใหม่อีกครั้ง'}
          </AlertDescription>
        </Alert>
        <Button
          onClick={fetchVotingStatus}
          variant="outline"
          className="mt-4 w-full"
        >
          ลองใหม่อีกครั้ง
        </Button>
      </div>
    );
  }

  // Success state
  if (showSuccess) {
    return <VoteSuccessState onReset={handleReset} />;
  }

  // Voting closed
  if (!votingStatus.votingEnabled || !votingStatus.isWithinPeriod) {
    return (
      <VotingClosedState
        votingEnabled={votingStatus.votingEnabled}
        isWithinPeriod={votingStatus.isWithinPeriod}
        votingStartDate={votingStatus.votingStartDate}
        votingEndDate={votingStatus.votingEndDate}
      />
    );
  }

  // Already voted max
  if (votingStatus.voteCount >= votingStatus.maxVotes) {
    return (
      <AlreadyVotedState
        voteCount={votingStatus.voteCount}
        maxVotes={votingStatus.maxVotes}
      />
    );
  }

  // Can vote
  const remaining = votingStatus.maxVotes - votingStatus.voteCount;
  const canSelectMore = selectedIds.size < remaining;
  const selectedCandidates = votingStatus.candidates.filter((c) =>
    selectedIds.has(c.id)
  );

  return (
    <div className="w-full max-w-4xl mx-auto p-4 sm:p-6 space-y-6">
      {/* Header */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
        className="text-center space-y-3"
      >
        <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">
          <Vote 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-3xl sm:text-4xl font-bold text-foreground">
          {votingStatus.branch.name}
        </h1>
        <p className="text-muted-foreground text-sm sm:text-base">
          คุณสามารถเลือกผู้สมัครจากสาขาของคุณเท่านั้น
        </p>
      </motion.div>

      {/* Info Cards */}
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.1 }}
        className="grid grid-cols-1 sm:grid-cols-2 gap-4"
      >
        {/* Votes Remaining */}
        <Card className="border-emerald-200 dark:border-emerald-800/50">
          <CardContent className="p-4 flex items-center gap-4">
            <div className="shrink-0 w-12 h-12 rounded-xl bg-emerald-100 dark:bg-emerald-900/40 flex items-center justify-center">
              <UserCheck className="size-6 text-emerald-600 dark:text-emerald-400" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm text-muted-foreground">คะแนนที่เหลือ</p>
              <p className="text-xl font-bold text-emerald-700 dark:text-emerald-300">
                เหลืออีก {remaining} จาก {votingStatus.maxVotes} คะแนน
              </p>
              <Progress
                value={(votingStatus.voteCount / votingStatus.maxVotes) * 100}
                className="mt-2 h-2 bg-emerald-100 dark:bg-emerald-950/40 [&>[data-slot=progress-indicator]]:bg-emerald-500"
              />
            </div>
          </CardContent>
        </Card>

        {/* Anonymous notice */}
        <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-4">
            <div className="shrink-0 w-12 h-12 rounded-xl bg-amber-100 dark:bg-amber-900/40 flex items-center justify-center">
              <ShieldCheck className="size-6 text-amber-600 dark:text-amber-400" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm text-muted-foreground">การลงคะแนนเป็นความลับ</p>
              <p className="text-sm font-medium text-amber-700 dark:text-amber-300">
                การลงคะแนนของคุณเป็นการไม่เปิดเผยตัวตน
              </p>
            </div>
          </CardContent>
        </Card>
      </motion.div>

      {/* Selection Summary */}
      {selectedIds.size > 0 && (
        <motion.div
          initial={{ opacity: 0, height: 0 }}
          animate={{ opacity: 1, height: 'auto' }}
          exit={{ opacity: 0, height: 0 }}
          transition={{ duration: 0.2 }}
        >
          <Alert className="border-emerald-200 dark:border-emerald-800 bg-emerald-50/50 dark:bg-emerald-950/20">
            <CheckCircle2 className="size-4 text-emerald-600 dark:text-emerald-400" />
            <AlertTitle className="text-emerald-700 dark:text-emerald-300">
              เลือกแล้ว {selectedIds.size} คน
            </AlertTitle>
            <AlertDescription className="text-emerald-600/80 dark:text-emerald-400/80">
              {selectedCandidates.map((c) => c.name).join(' • ')}
            </AlertDescription>
          </Alert>
        </motion.div>
      )}

      {/* Candidate Grid */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold text-foreground flex items-center gap-2">
            <Users className="size-5 text-emerald-600 dark:text-emerald-400" />
            รายชื่อผู้สมัคร
          </h2>
          <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"
          >
            {votingStatus.candidates.length} คน
          </Badge>
        </div>

        {votingStatus.candidates.length === 0 ? (
          <Card className="py-8">
            <CardContent className="flex flex-col items-center justify-center text-center p-6">
              <Users className="size-12 text-muted-foreground/40 mb-3" />
              <p className="text-muted-foreground">
                ยังไม่มีรายชื่อผู้สมัครในสาขาของคุณ
              </p>
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            <AnimatePresence mode="popLayout">
              {votingStatus.candidates.map((candidate, index) => {
                const isSelected = selectedIds.has(candidate.id);
                const isDisabled = !isSelected && !canSelectMore;

                return (
                  <motion.div
                    key={candidate.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.3, delay: index * 0.05 }}
                    layout
                  >
                    <CandidateCard
                      candidate={candidate}
                      isSelected={isSelected}
                      isDisabled={isDisabled}
                      onToggle={() => toggleCandidate(candidate.id)}
                    />
                  </motion.div>
                );
              })}
            </AnimatePresence>
          </div>
        )}
      </div>

      {/* Submit Button */}
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.2 }}
        className="sticky bottom-4 z-10"
      >
        <Card className="border-emerald-200 dark:border-emerald-800/50 shadow-lg shadow-emerald-100/50 dark:shadow-emerald-950/30">
          <CardContent className="p-4 flex flex-col sm:flex-row items-center gap-4">
            <div className="flex-1 text-center sm:text-left">
              <p className="text-sm text-muted-foreground">
                {selectedIds.size > 0
                  ? `เลือกแล้ว ${selectedIds.size} จาก ${remaining} คะแนนที่สามารถใช้ได้`
                  : 'กรุณาเลือกผู้สมัครที่ต้องการลงคะแนน'}
              </p>
            </div>
            <Button
              size="lg"
              disabled={selectedIds.size === 0 || submitting}
              onClick={() => setConfirmOpen(true)}
              className="w-full sm:w-auto bg-emerald-600 hover:bg-emerald-700 text-white shadow-md min-w-[200px]"
            >
              {submitting ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  กำลังบันทึก...
                </>
              ) : (
                <>
                  <Vote className="size-4" />
                  ยืนยันการลงคะแนน
                  {selectedIds.size > 0 && (
                    <Badge className="ml-1 bg-white/20 text-white border-0 hover:bg-white/30">
                      {selectedIds.size}
                    </Badge>
                  )}
                </>
              )}
            </Button>
          </CardContent>
        </Card>
      </motion.div>

      {/* Confirmation Dialog */}
      <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <div className="flex items-center gap-3 mb-2">
              <div className="w-10 h-10 rounded-full bg-amber-100 dark:bg-amber-900/40 flex items-center justify-center shrink-0">
                <AlertTriangle className="size-5 text-amber-600 dark:text-amber-400" />
              </div>
              <AlertDialogTitle>ยืนยันการลงคะแนน</AlertDialogTitle>
            </div>
            <AlertDialogDescription asChild>
              <div className="space-y-4">
                <p className="text-muted-foreground">
                  คุณต้องการลงคะแนนให้ผู้สมัครต่อไปนี้หรือไม่?
                  <br />
                  <span className="text-amber-600 dark:text-amber-400 font-medium">
                    การลงคะแนนไม่สามารถเปลี่ยนแปลงได้หลังจากยืนยันแล้ว
                  </span>
                </p>

                <div className="bg-muted/50 rounded-lg p-3 space-y-2">
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    ผู้สมัครที่เลือก ({selectedCandidates.length} คน)
                  </p>
                  {selectedCandidates.map((candidate, i) => (
                    <div
                      key={candidate.id}
                      className="flex items-center gap-3 text-sm"
                    >
                      <div className="w-7 h-7 rounded-full bg-emerald-100 dark:bg-emerald-900/50 flex items-center justify-center text-xs font-bold text-emerald-700 dark:text-emerald-300 shrink-0">
                        {i + 1}
                      </div>
                      <div>
                        <span className="font-medium">{candidate.name}</span>
                        {candidate.position && (
                          <span className="text-muted-foreground ml-2">
                            — {candidate.position}
                          </span>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={submitting}>ยกเลิก</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleSubmit}
              disabled={submitting}
              className="bg-emerald-600 hover:bg-emerald-700 text-white"
            >
              {submitting ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  กำลังบันทึก...
                </>
              ) : (
                <>
                  <CheckCircle2 className="size-4" />
                  ยืนยันลงคะแนน
                </>
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
