import { useState } from 'react';
import { router, usePage } from '@inertiajs/react';
import { Crown, Users, Vote, CheckCircle2, Eye, EyeOff, ChevronDown, MessageSquare } from 'lucide-react';
import AuthenticatedLayout from '@/layouts/AuthenticatedLayout';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';

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

interface Props extends PageProps {
    session: {
        id: number;
        title: string;
        type: 'class_election' | 'quick_poll';
        results_visible: boolean;
        synced_class: { name: string };
    };
    results: Array<{
        position: { id: number; name: string };
        candidates: Array<{
            id: number;
            student: Student | null;
            label: string | null;
            final_votes_count: number;
        }>;
        total_votes: number;
    }>;
    totalStudents: number;
    voterDetails: Record<number, Array<{
        id: number;
        voter: Student;
        candidate: {
            id: number;
            student: Student | null;
            label: string | null;
        };
    }>>;
}

export default function VotingResults() {
    const { session, results, totalStudents, voterDetails } = usePage<Props>().props;
    const [activePositionId, setActivePositionId] = useState<number>(results[0]?.position.id || 0);
    const [expandedCandidates, setExpandedCandidates] = useState<Record<number, boolean>>({});

    const isQuickPoll = session.type === 'quick_poll';

    const toggleExpandCandidate = (candidateId: number) => {
        setExpandedCandidates(prev => ({
            ...prev,
            [candidateId]: !prev[candidateId]
        }));
    };

    const activeResult = results.find(r => r.position.id === activePositionId);
    const activeVotes = voterDetails[activePositionId] || [];

    const handleToggleVisibility = () => {
        router.post(`/voting/${session.id}/toggle-results`);
    };

    return (
        <AuthenticatedLayout title={`Hasil: ${session.title}`} backHref={`/voting/${session.id}`}>
            {/* Header */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
                <div>
                    <p className="text-sm text-text-muted">Hasil akhir {isQuickPoll ? 'voting' : 'pemilihan'}.</p>
                </div>
                <div className="flex items-center gap-3">
                    <div className={cn(
                        'flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold border',
                        session.results_visible 
                            ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20' 
                            : 'bg-surface-hover text-text-muted border-border'
                    )}>
                        {session.results_visible ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
                        {session.results_visible ? 'Dipublikasikan' : 'Disembunyikan'}
                    </div>
                    <button
                        onClick={handleToggleVisibility}
                        className="rounded-xl bg-surface-hover px-4 py-2 text-sm font-semibold hover:bg-surface-hover/80 transition-colors"
                    >
                        Ubah Visibilitas
                    </button>
                </div>
            </div>

            <div className="grid lg:grid-cols-3 gap-6">
                {/* Main Results */}
                <div className="lg:col-span-2 space-y-6">
                    {results.map((result) => {
                        const winner = result.candidates.length > 0 && result.candidates[0].final_votes_count > 0 ? result.candidates[0] : null;
                        
                        return (
                            <div key={result.position.id} className="rounded-2xl border border-border/50 bg-surface/60 backdrop-blur-sm p-6">
                                <div className="flex items-center justify-between mb-6">
                                    {isQuickPoll ? (
                                        <h3 className="text-xl font-bold flex items-center gap-2">
                                            <MessageSquare className="h-6 w-6 text-primary-400" />
                                            Daftar Pilihan
                                        </h3>
                                    ) : (
                                        <h3 className="text-xl font-bold flex items-center gap-2">
                                            <Crown className="h-6 w-6 text-primary-400" />
                                            {result.position.name}
                                        </h3>
                                    )}
                                    <span className="text-sm text-text-muted bg-surface-hover px-3 py-1 rounded-full">
                                        Total: {result.total_votes} suara
                                    </span>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    {result.candidates.map((candidate, idx) => {
                                        const isWinner = winner && winner.id === candidate.id;
                                        const percentage = result.total_votes > 0 
                                            ? Math.round((candidate.final_votes_count / result.total_votes) * 100) 
                                            : 0;

                                        const label = candidate.label || candidate.student?.full_name || 'Tidak diketahui';

                                        return (
                                            <div 
                                                key={candidate.id}
                                                className={cn(
                                                    'relative overflow-hidden rounded-xl border p-4 transition-all duration-300 flex flex-col justify-between min-h-[130px] shadow-sm',
                                                    isWinner 
                                                        ? 'border-emerald-500/40 bg-surface/60 shadow-md shadow-emerald-950/20' 
                                                        : 'border-border/40 bg-surface/30 hover:bg-surface/50 hover:border-border/80'
                                                )}
                                            >
                                                {/* Left indicator border for winner */}
                                                {isWinner && (
                                                    <div className="absolute left-0 top-0 bottom-0 w-1 bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.8)]" />
                                                )}

                                                <div className="relative z-10 space-y-3">
                                                    {/* Top Details */}
                                                    <div className="flex items-start justify-between gap-3">
                                                        <div className="flex items-start gap-3">
                                                            <div className={cn(
                                                                'w-8 h-8 rounded-full flex items-center justify-center font-bold text-xs shadow-inner shrink-0',
                                                                isWinner 
                                                                    ? 'bg-emerald-500 text-white shadow-emerald-500/40' 
                                                                    : 'bg-surface-hover text-text border border-border/50'
                                                            )}>
                                                                {idx + 1}
                                                            </div>
                                                            <div>
                                                                <p className={cn('font-bold text-sm leading-snug line-clamp-2 capitalize', isWinner ? 'text-emerald-400' : 'text-text')}>
                                                                    {label}
                                                                </p>
                                                                {isWinner && (
                                                                    <span className="inline-flex items-center gap-1 text-[9px] text-emerald-400 bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20 font-medium mt-1">
                                                                        <CheckCircle2 className="w-2.5 h-2.5" /> Terpilih
                                                                    </span>
                                                                )}
                                                            </div>
                                                        </div>
                                                        
                                                        {/* Votes info */}
                                                        <div className="text-right shrink-0">
                                                            <p className={cn('text-base font-black tracking-tight leading-none', isWinner ? 'text-emerald-400' : 'text-text')}>
                                                                {candidate.final_votes_count} <span className="text-[10px] font-normal text-text-muted">suara</span>
                                                            </p>
                                                            <p className="text-[10px] text-text-muted mt-0.5 font-medium">{percentage}%</p>
                                                        </div>
                                                    </div>

                                                    {/* Bottom Progress Bar */}
                                                    <div className="space-y-1 mt-auto pt-2">
                                                        <div className="flex items-center justify-between text-[10px] text-text-muted">
                                                            <span>Persentase Suara</span>
                                                            <span className="font-semibold">{percentage}%</span>
                                                        </div>
                                                        <div className="h-1.5 w-full bg-surface-hover rounded-full overflow-hidden border border-border/30">
                                                            <div 
                                                                className={cn(
                                                                    'h-full rounded-full transition-all duration-1000',
                                                                    isWinner 
                                                                        ? 'bg-linear-to-r from-emerald-500 to-teal-500 shadow-[0_0_8px_rgba(16,185,129,0.4)]' 
                                                                        : 'bg-linear-to-r from-primary-500 to-primary-600'
                                                                )}
                                                                style={{ width: `${percentage}%` }}
                                                            />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        );
                    })}
                </div>

                {/* Sidebar Details (Guru only) */}
                <div className="space-y-6">
                    <div className="app-eco-solid-surface rounded-2xl border border-border/50 bg-surface/60 backdrop-blur-sm p-6 sticky top-6">
                        <h3 className="font-semibold flex items-center gap-2 mb-2">
                            <Users className="h-5 w-5 text-primary-400" />
                            Rincian Pemilih
                        </h3>
                        <p className="text-[11px] text-text-muted mb-4 border-b border-border/50 pb-4 leading-normal">
                            Log ini hanya terlihat oleh guru. Siswa tidak dapat melihat siapa memilih siapa.
                        </p>

                        {/* Position Tabs */}
                        {!isQuickPoll && results.length > 1 && (
                            <div className="flex flex-wrap gap-1.5 mb-4 p-1 bg-surface-hover/30 rounded-xl border border-border/30">
                                {results.map(result => (
                                    <button
                                        key={result.position.id}
                                        onClick={() => setActivePositionId(result.position.id)}
                                        className={cn(
                                            "flex-1 px-3 py-1.5 text-xs font-semibold rounded-lg transition-all whitespace-nowrap",
                                            activePositionId === result.position.id
                                                ? "bg-primary-500 text-white shadow-sm shadow-primary-500/20"
                                                : "text-text-muted hover:text-text hover:bg-surface-hover/50"
                                        )}
                                    >
                                        {result.position.name}
                                    </button>
                                ))}
                            </div>
                        )}

                        <div className="space-y-3 max-h-[500px] overflow-y-auto pr-1 custom-scrollbar">
                            {activeResult ? (
                                activeResult.candidates.length === 0 ? (
                                    <p className="text-xs text-text-muted italic text-center py-4">Tidak ada pilihan</p>
                                ) : (
                                    activeResult.candidates.map((candidate, idx) => {
                                        const candidateVotes = activeVotes.filter(vote => vote.candidate.id === candidate.id);
                                        const isExpanded = expandedCandidates[candidate.id] !== false;
                                        const label = candidate.label || candidate.student?.full_name || 'Tidak diketahui';

                                        return (
                                            <div key={candidate.id} className="border border-border/40 rounded-xl overflow-hidden bg-surface/30">
                                                <button
                                                    onClick={() => toggleExpandCandidate(candidate.id)}
                                                    className="w-full flex items-center justify-between p-3 text-left hover:bg-surface-hover/35 transition-colors"
                                                >
                                                    <div className="flex items-center gap-2">
                                                        <div className="w-6 h-6 rounded-full bg-surface-hover border border-border/50 flex items-center justify-center text-[10px] font-bold text-text">
                                                            {idx + 1}
                                                        </div>
                                                        <span className="text-xs font-bold text-text line-clamp-1 capitalize">{label}</span>
                                                    </div>
                                                    <div className="flex items-center gap-2">
                                                        <span className="text-[9px] font-semibold text-text-muted bg-surface-hover/80 px-2 py-0.5 rounded-full border border-border/30">
                                                            {candidateVotes.length} Pemilih
                                                        </span>
                                                        <ChevronDown className={cn("w-3.5 h-3.5 text-text-muted transition-transform duration-200", isExpanded && "rotate-180")} />
                                                    </div>
                                                </button>

                                                {isExpanded && (
                                                    <div className="p-3 bg-surface-hover/10 border-t border-border/30">
                                                        {candidateVotes.length === 0 ? (
                                                            <p className="text-[10px] text-text-muted italic py-1 pl-1">Belum ada pemilih untuk pilihan ini</p>
                                                        ) : (
                                                            <div className="flex flex-wrap gap-1.5">
                                                                {candidateVotes.map(vote => (
                                                                    <span
                                                                        key={vote.id}
                                                                        className="inline-flex items-center text-[10px] font-medium text-text bg-surface/80 border border-border/40 px-2 py-1 rounded-lg shadow-sm"
                                                                    >
                                                                        {vote.voter.full_name}
                                                                    </span>
                                                                ))}
                                                            </div>
                                                        )}
                                                    </div>
                                                )}
                                            </div>
                                        );
                                    })
                                )
                            ) : (
                                <p className="text-xs text-text-muted italic text-center py-4">Data tidak ditemukan</p>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
