import { confirmAction } from '@/lib/confirm-action';
import { Link, useForm, usePage } from '@inertiajs/react';
import { ArrowLeft, Vote, CheckCircle2, ShieldAlert, MessageSquare } from 'lucide-react';
import StudentLayout from '@/layouts/StudentLayout';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';
import { toast } from 'sonner';
import { useState } from 'react';

interface Student {
    id: number;
    full_name: string;
    gender: 'L' | 'P' | null;
}

interface Candidate {
    id: number;
    student: Student | null;
    label: string | null;
}

interface Position {
    id: number;
    name: string;
}

interface Props extends PageProps {
    session: {
        id: number;
        title: string;
        type: 'class_election' | 'quick_poll';
        positions: Position[];
    };
    candidatesByPosition: Record<number, Candidate[]>;
    studentId: number;
    existingVotes: Record<number, number>; // position_id => voting_candidate_id
}

export default function VoteForm() {
    const { session, candidatesByPosition, existingVotes } = usePage<Props>().props;
    
    const hasVoted = Object.keys(existingVotes).length > 0;
    const isQuickPoll = session.type === 'quick_poll';
    const [isEditing, setIsEditing] = useState(!hasVoted);

    const { data, setData, post, processing } = useForm({
        votes: hasVoted ? existingVotes : {} as Record<number, number>,
    });

    const handleSelectCandidate = (positionId: number, candidateId: number) => {
        if (!isEditing) return;
        setData('votes', {
            ...data.votes,
            [positionId]: candidateId
        });
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        
        const missing = session.positions.some(p => !data.votes[p.id]);
        if (missing) {
            toast.error(isQuickPoll ? 'Mohon pilih satu pilihan sebelum mengirim.' : 'Mohon pilih satu kandidat untuk setiap posisi sebelum mengirim.');
            return;
        }

        if ((await confirmAction('Kirim suara Anda?'))) {
            post(`/student/voting/${session.id}/vote`, {
                onSuccess: () => {
                    toast.success('Suara berhasil dikirim!');
                }
            });
        }
    };

    return (
        <StudentLayout title={`${isQuickPoll ? 'Polling' : 'Pemilihan'}: ${session.title}`}>
            <div className="max-w-2xl mx-auto px-2 sm:px-0">
                <Link href="/student/voting" className="inline-flex items-center gap-1.5 md:gap-2 text-[10px] md:text-sm text-text-muted hover:text-text transition-colors mb-4 md:mb-6">
                    <ArrowLeft className="h-3 w-3 md:h-4 md:w-4" />
                    Kembali
                </Link>

                <div className="rounded-xl md:rounded-2xl border border-border/50 bg-linear-to-br from-surface/80 to-surface/40 backdrop-blur-md overflow-hidden shadow-lg shadow-black/5">
                    <div className="p-4 md:p-6 border-b border-border/50 bg-linear-to-r from-emerald-500/10 to-transparent">
                        <div className="flex items-center gap-2.5 md:gap-4 mb-2 md:mb-3">
                            <div className="w-8 h-8 md:w-12 md:h-12 shrink-0 rounded-xl md:rounded-2xl bg-linear-to-br from-emerald-500/20 to-emerald-500/5 flex items-center justify-center border border-emerald-500/20 shadow-inner">
                                {isQuickPoll ? <MessageSquare className="h-4 w-4 md:h-6 md:w-6 text-emerald-400" /> : <Vote className="h-4 w-4 md:h-6 md:w-6 text-emerald-400" />}
                            </div>
                            <div>
                                <h1 className="text-sm md:text-xl font-bold bg-clip-text text-transparent bg-linear-to-r from-text to-text-muted/80">Sesi 2: {isQuickPoll ? 'Polling Final' : 'Pemilihan Final'}</h1>
                                <p className="text-[10px] md:text-sm text-text-muted mt-0.5">{session.title}</p>
                            </div>
                        </div>
                        <div className="text-[9px] md:text-sm text-emerald-400/90 bg-emerald-500/10 border border-emerald-500/20 p-2.5 md:p-4 rounded-lg md:rounded-xl flex items-start gap-2 mt-3 md:mt-4 shadow-sm">
                            <ShieldAlert className="w-3.5 h-3.5 md:w-5 md:h-5 shrink-0 mt-0.5 md:mt-0.5" />
                            <p className="leading-relaxed">
                                {isQuickPoll 
                                    ? 'Pilih opsi yang paling sesuai. Suaramu bersifat rahasia dan tidak dapat diubah setelah dikirim.'
                                    : 'Pilih kandidat terbaik untuk memimpin kelasmu. Suaramu bersifat rahasia dan tidak dapat diubah setelah dikirim.'}
                            </p>
                        </div>
                    </div>

                    <form onSubmit={handleSubmit} className="p-4 md:p-6 space-y-4 md:space-y-6">
                        {session.positions.map(pos => {
                            const candidates = candidatesByPosition[pos.id] || [];
                            
                            return (
                                <div key={pos.id} className="rounded-xl md:rounded-2xl border border-border/50 p-3.5 md:p-5 bg-surface/40 hover:bg-surface/60 transition-colors">
                                    {!isQuickPoll && <h3 className="font-semibold text-xs md:text-lg mb-2.5 md:mb-4">{pos.name}</h3>}
                                    {isQuickPoll && session.positions.length > 1 && <h3 className="font-semibold text-xs md:text-lg mb-2.5 md:mb-4">{pos.name}</h3>}
                                    
                                    {candidates.length === 0 ? (
                                        <p className="text-[10px] md:text-sm text-text-muted italic bg-surface-hover/50 p-3 md:p-4 rounded-lg md:rounded-xl border border-border/50 text-center">Tidak ada {isQuickPoll ? 'pilihan' : 'kandidat'} untuk {isQuickPoll ? 'polling' : 'posisi'} ini.</p>
                                    ) : (
                                        <div className="grid gap-2.5 md:gap-3 md:grid-cols-2">
                                            {candidates.map(candidate => {
                                                const isSelected = data.votes[pos.id] === candidate.id;
                                                const label = candidate.label || candidate.student?.full_name || 'Tidak diketahui';
                                                return (
                                                    <button
                                                        key={candidate.id}
                                                        type="button"
                                                        disabled={!isEditing}
                                                        onClick={() => handleSelectCandidate(pos.id, candidate.id)}
                                                        className={cn(
                                                            'flex items-center p-2.5 md:p-4 rounded-lg md:rounded-xl border text-left transition-all duration-300 relative overflow-hidden group',
                                                            isSelected 
                                                                ? 'border-emerald-500 bg-linear-to-r from-emerald-500/15 to-emerald-500/5 shadow-md shadow-emerald-500/10 ring-1 ring-emerald-500/50 scale-[1.02]' 
                                                                : 'border-border/60 hover:border-emerald-500/40 hover:bg-surface-hover/80 hover:shadow-sm',
                                                            !isEditing && !isSelected && 'opacity-40 grayscale-50'
                                                        )}
                                                    >
                                                        {isSelected && (
                                                            <div className="absolute left-0 top-0 bottom-0 w-1 md:w-1.5 bg-linear-to-b from-emerald-400 to-emerald-600 shadow-[0_0_8px_rgba(16,185,129,0.5)]" />
                                                        )}
                                                        
                                                        <div className="flex items-center gap-2.5 md:gap-4 flex-1 ml-1.5 md:ml-2">
                                                            <div className={cn(
                                                                "w-8 h-8 md:w-12 md:h-12 rounded-full flex items-center justify-center font-bold text-[10px] md:text-base transition-colors shadow-inner shrink-0",
                                                                isSelected 
                                                                    ? "bg-emerald-500 text-white shadow-emerald-500/50" 
                                                                    : "bg-linear-to-br from-primary-500/20 to-primary-500/5 text-primary-400 border border-primary-500/20 group-hover:border-emerald-500/30"
                                                            )}>
                                                                {label.charAt(0).toUpperCase()}
                                                            </div>
                                                            <div className="flex-1 min-w-0">
                                                                <p className={cn('font-semibold text-[11px] md:text-base transition-colors truncate capitalize', isSelected ? 'text-emerald-400' : 'text-text group-hover:text-emerald-400/80')}>
                                                                    {label}
                                                                </p>
                                                            </div>
                                                        </div>
                                                        <div className={cn(
                                                            'w-4 h-4 md:w-6 md:h-6 rounded-full border-[1.5px] md:border-2 flex items-center justify-center shrink-0 ml-2 md:ml-3 transition-colors',
                                                            isSelected ? 'border-emerald-500 bg-emerald-500' : 'border-border/60 group-hover:border-emerald-500/50'
                                                        )}>
                                                            {isSelected && <CheckCircle2 className="w-2.5 h-2.5 md:w-4 md:h-4 text-white" />}
                                                        </div>
                                                    </button>
                                                );
                                            })}
                                        </div>
                                    )}
                                </div>
                            );
                        })}

                        {!isEditing ? (
                            <div className="p-3 md:p-4 rounded-lg md:rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-center flex flex-col items-center gap-3">
                                <div className="flex flex-col items-center">
                                    <CheckCircle2 className="w-6 h-6 md:w-8 md:h-8 mb-1.5 md:mb-2" />
                                    <p className="font-medium text-[11px] md:text-base">Kamu sudah memberikan suara.</p>
                                    <p className="text-[9px] md:text-sm mt-0.5 md:mt-1 opacity-80">Kamu bisa mengubahnya selama sesi masih terbuka.</p>
                                </div>
                                <button
                                    type="button"
                                    onClick={() => setIsEditing(true)}
                                    className="rounded-lg md:rounded-xl bg-emerald-500/20 border border-emerald-500/30 px-4 md:px-6 py-2 md:py-2.5 text-[11px] md:text-sm font-semibold text-emerald-400 hover:bg-emerald-500/30 transition-colors"
                                >
                                    Ubah Suara
                                </button>
                            </div>
                        ) : (
                            <button
                                type="submit"
                                disabled={processing || session.positions.some(p => !data.votes[p.id])}
                                className="w-full rounded-lg md:rounded-xl bg-emerald-500 px-4 md:px-6 py-2.5 md:py-3 text-[11px] md:text-sm font-semibold text-white shadow-lg shadow-emerald-500/25 transition-all hover:bg-emerald-600 disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                {processing ? 'Mengirim...' : (hasVoted ? 'Perbarui Suara Saya' : 'Kirim Suara Saya')}
                            </button>
                        )}
                    </form>
                </div>
            </div>
        </StudentLayout>
    );
}
