import { Link, usePage } from '@inertiajs/react';
import { Vote, Plus, Users, CheckCircle2, Clock, Eye, MessageSquare } from 'lucide-react';
import AuthenticatedLayout from '@/layouts/AuthenticatedLayout';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';

interface VotingSession {
    id: number;
    title: string;
    type: 'class_election' | 'quick_poll';
    mode: 'open_nomination' | 'teacher_assigned';
    current_phase: 'nomination' | 'review' | 'final_vote' | 'completed';
    min_votes_threshold: number;
    max_suggestions: number;
    results_visible: boolean;
    created_at: string;
    candidates_count: number;
    synced_class: { id: number; name: string };
    positions: Array<{ id: number; name: string; sort_order: number }>;
    started_at: string | null;
    end_at: string | null;
}

interface HomeroomClass {
    id: number;
    name: string;
    students_count: number;
}

interface Props extends PageProps {
    sessions: VotingSession[];
    homeroomClasses: HomeroomClass[];
}

const phaseConfig = {
    nomination: { label: 'Nominasi', color: 'bg-amber-500/20 text-amber-400 ring-amber-500/30', icon: Users },
    review: { label: 'Review', color: 'bg-sky-500/20 text-sky-400 ring-sky-500/30', icon: Eye },
    final_vote: { label: 'Pemilihan', color: 'bg-emerald-500/20 text-emerald-400 ring-emerald-500/30', icon: Vote },
    completed: { label: 'Selesai', color: 'bg-slate-500/20 text-slate-400 ring-slate-500/30', icon: CheckCircle2 },
};

export default function VotingIndex() {
    const { sessions, homeroomClasses } = usePage<Props>().props;

    if (homeroomClasses.length === 0) {
        return (
            <>
                <div className="flex flex-col items-center justify-center py-24 text-center">
                    <div className="w-20 h-20 rounded-2xl bg-surface-hover/50 flex items-center justify-center mb-6">
                        <Vote className="w-10 h-10 text-text-muted" />
                    </div>
                    <h2 className="text-xl font-semibold mb-2">Tidak Ada Akses</h2>
                    <p className="text-text-muted max-w-md">
                        Anda belum terdaftar sebagai wali kelas. Menu voting hanya tersedia untuk wali kelas.
                        Hubungi admin untuk mengatur wali kelas melalui data sync.
                    </p>
                </div>
            </>
        );
    }

    return (
        <>
            {/* Header */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
                <div>
                    <p className="text-sm text-text-muted">
                        Kelola pemilihan pengurus dan polling kelas untuk {homeroomClasses.map(c => c.name).join(', ')}
                    </p>
                </div>
                <Link
                    href="/voting/create"
                    className="inline-flex items-center gap-2 rounded-xl bg-primary-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-primary-500/25 transition-all hover:bg-primary-600 hover:shadow-primary-500/40 hover:-translate-y-0.5 active:translate-y-0"
                >
                    <Plus className="h-4 w-4" />
                    Buat Sesi Baru
                </Link>
            </div>

            {/* Sessions Grid */}
            {sessions.length === 0 ? (
                <div className="rounded-2xl border border-border/50 bg-surface/60 backdrop-blur-sm p-12 text-center">
                    <div className="w-16 h-16 rounded-2xl bg-primary-500/10 flex items-center justify-center mx-auto mb-4">
                        <Vote className="w-8 h-8 text-primary-400" />
                    </div>
                    <h3 className="text-lg font-semibold mb-2">Belum Ada Sesi Voting</h3>
                    <p className="text-text-muted mb-6">Buat sesi voting pertama untuk memulai pemilihan pengurus atau polling kelas.</p>
                    <Link
                        href="/voting/create"
                        className="inline-flex items-center gap-2 rounded-xl bg-primary-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-primary-500/25 transition-all hover:bg-primary-600"
                    >
                        <Plus className="h-4 w-4" />
                        Buat Sesi Baru
                    </Link>
                </div>
            ) : (
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    {sessions.map((session) => {
                        const phase = phaseConfig[session.current_phase];
                        const isQuickPoll = session.type === 'quick_poll';
                        
                        const now = new Date();
                        const serverTimeBuffer = 5 * 60 * 1000;
                        const nowWithBuffer = new Date(now.getTime() + serverTimeBuffer);

                        const isLive = session.started_at && new Date(session.started_at) <= nowWithBuffer && (!session.end_at || new Date(session.end_at) > now);
                        const isDraft = !session.started_at;
                        const isScheduled = session.started_at && new Date(session.started_at) > nowWithBuffer;
                        const isPastEnd = session.end_at && new Date(session.end_at) <= now;

                        let phaseLabel = phase.label;
                        let phaseColor = phase.color;
                        let PhaseIcon = phase.icon;

                        if (isDraft) {
                            phaseLabel = 'Draft';
                            phaseColor = 'bg-amber-500/20 text-amber-400 ring-amber-500/30';
                            PhaseIcon = Clock;
                        } else if (isScheduled) {
                            phaseLabel = 'Terjadwal';
                            phaseColor = 'bg-sky-500/20 text-sky-400 ring-sky-500/30';
                            PhaseIcon = Clock;
                        } else if (isPastEnd && session.current_phase !== 'completed') {
                            phaseLabel = 'Selesai (Jadwal)';
                            phaseColor = 'bg-slate-500/20 text-slate-400 ring-slate-500/30';
                            PhaseIcon = CheckCircle2;
                        }

                        return (
                            <Link
                                key={session.id}
                                href={session.current_phase === 'completed' ? `/voting/${session.id}/results` : `/voting/${session.id}`}
                                className="group rounded-2xl border border-border/50 bg-surface/60 backdrop-blur-sm p-5 transition-all hover:border-primary-500/30 hover:shadow-lg hover:shadow-primary-500/5 hover:-translate-y-0.5"
                            >
                                {/* Phase Badge */}
                                <div className="flex items-center justify-between mb-4">
                                    <span className={cn('inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-xs font-semibold ring-1', phaseColor)}>
                                        <PhaseIcon className="h-3 w-3" />
                                        {phaseLabel}
                                    </span>
                                    <span className="text-xs text-text-muted">
                                        {new Date(session.created_at).toLocaleDateString('id-ID', { day: 'numeric', month: 'short' })}
                                    </span>
                                </div>

                                {/* Title */}
                                <h3 className="font-semibold text-lg mb-1 group-hover:text-primary-400 transition-colors flex items-center gap-2">
                                    {isQuickPoll ? <MessageSquare className="h-4 w-4 text-primary-400" /> : <Vote className="h-4 w-4 text-primary-400" />}
                                    {session.title}
                                </h3>
                                <p className="text-sm text-text-muted mb-4">
                                    Kelas {session.synced_class.name}
                                </p>

                                {/* Positions / Poll Indicator */}
                                <div className="flex flex-wrap gap-1.5">
                                    {isQuickPoll ? (
                                        <span className="rounded-md bg-surface-hover px-2 py-0.5 text-xs font-medium text-primary-300">
                                            Polling Cepat
                                        </span>
                                    ) : (
                                        session.positions.map((pos) => (
                                            <span
                                                key={pos.id}
                                                className="rounded-md bg-surface-hover px-2 py-0.5 text-xs text-text-muted"
                                            >
                                                {pos.name}
                                            </span>
                                        ))
                                    )}
                                </div>

                                {/* Footer */}
                                <div className="mt-4 pt-3 border-t border-border/50 flex items-center justify-between text-xs text-text-muted">
                                    <span className="capitalize">{session.mode === 'open_nomination' ? (isQuickPoll ? 'Usulan Terbuka' : 'Nominasi Terbuka') : 'Guru Menentukan'}</span>
                                    <span>
                                        {isQuickPoll && session.mode === 'open_nomination' 
                                            ? `Maks ${session.max_suggestions} Pilihan`
                                            : `Min. ${session.min_votes_threshold} suara`}
                                    </span>
                                </div>
                            </Link>
                        );
                    })}
                </div>
            )}
        </>
    );
}

VotingIndex.layout = (page: any) => <AuthenticatedLayout title="Voting Kelas">{page}</AuthenticatedLayout>;
