import React, { useEffect } from 'react';
import { Head, Link, usePage } from '@inertiajs/react';
import { Trophy, Target, Flame, ArrowLeft, RotateCcw } from 'lucide-react';
import confetti from 'canvas-confetti';
import type { PageProps } from '@/types';

interface ResultProps extends PageProps {
    attempt: {
        id: number;
        total_score: number;
        total_correct: number;
        total_questions: number;
        accuracy_percentage: number;
        longest_streak: number;
        average_speed_ms: number;
        game: {
            id: number;
            title: string;
            game_mode: string;
        };
    };
    factionLeaderboard?: Array<{
        class_id: number;
        class_name: string;
        total_score: number;
    }> | null;
}

export default function Result() {
    const { attempt, factionLeaderboard } = usePage<ResultProps>().props;

    useEffect(() => {
        // Ultimate confetti burst on load
        const duration = 3000;
        const end = Date.now() + duration;

        const frame = () => {
            confetti({
                particleCount: 5,
                angle: 60,
                spread: 55,
                origin: { x: 0 },
                colors: ['#10b981', '#fbbf24']
            });
            confetti({
                particleCount: 5,
                angle: 120,
                spread: 55,
                origin: { x: 1 },
                colors: ['#3b82f6', '#ef4444']
            });

            if (Date.now() < end) {
                requestAnimationFrame(frame);
            }
        };
        frame();
    }, []);

    const isPerfect = attempt.accuracy_percentage === 100;
    const isGood = attempt.accuracy_percentage >= 70;

    return (
        <div className="min-h-screen bg-slate-900 text-slate-100 flex flex-col items-center justify-center p-4 relative overflow-hidden">
            <Head title={`Hasil - ${attempt.game.title}`} />

            <div className="w-full max-w-lg relative z-10 text-center">
                
                <div className="mb-8 relative inline-block">
                    <div className="absolute inset-0 bg-amber-500 blur-3xl opacity-20 rounded-full"></div>
                    <Trophy className={`h-32 w-32 mx-auto drop-shadow-2xl ${isPerfect ? 'text-amber-300' : isGood ? 'text-amber-500' : 'text-slate-400'}`} />
                </div>

                <h1 className="text-4xl md:text-5xl font-black text-white mb-2">
                    {isPerfect ? 'SEMPURNA! 🎉' : isGood ? 'KERJA BAGUS! 👍' : 'COBA LAGI! 💪'}
                </h1>
                <p className="text-lg text-slate-400 mb-10">{attempt.game.title}</p>

                <div className="bg-slate-800/80 backdrop-blur-xl border border-slate-700/50 rounded-3xl p-8 shadow-2xl mb-8">
                    <div className="text-slate-400 text-sm font-bold uppercase tracking-widest mb-2">Total Skor</div>
                    <div className="text-6xl font-black text-emerald-400 drop-shadow-lg mb-8">
                        {attempt.total_score.toLocaleString()}
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div className="bg-slate-900/50 rounded-2xl p-4 border border-slate-700/50">
                            <Target className="h-6 w-6 text-sky-400 mx-auto mb-2" />
                            <div className="text-xs text-slate-400 uppercase tracking-wider font-bold mb-1">Akurasi</div>
                            <div className="text-2xl font-bold text-white">{attempt.accuracy_percentage}%</div>
                            <div className="text-xs text-slate-500 mt-1">{attempt.total_correct} dari {attempt.total_questions} benar</div>
                        </div>
                        <div className="bg-slate-900/50 rounded-2xl p-4 border border-slate-700/50">
                            <Flame className="h-6 w-6 text-orange-400 mx-auto mb-2" />
                            <div className="text-xs text-slate-400 uppercase tracking-wider font-bold mb-1">Streak Terbaik</div>
                            <div className="text-2xl font-bold text-white">{attempt.longest_streak}</div>
                            <div className="text-xs text-slate-500 mt-1">jawaban beruntun</div>
                        </div>
                    </div>
                </div>

                {attempt.game.game_mode === 'faction' && factionLeaderboard && (
                    <div className="bg-blue-500/10 border border-blue-500/20 rounded-3xl p-6 mb-8 text-left shadow-xl">
                        <div className="flex items-center justify-center gap-2 text-blue-400 font-bold mb-4 text-lg">
                            ⚔️ Klasemen Faction Wars Saat Ini
                        </div>
                        <div className="space-y-3">
                            {factionLeaderboard.map((faction, index) => (
                                <div key={faction.class_id} className={`flex items-center justify-between p-4 rounded-xl border ${index === 0 ? 'bg-amber-500/20 border-amber-500/40 shadow-[0_0_15px_rgba(245,158,11,0.2)]' : 'bg-slate-800/80 border-slate-700/50'}`}>
                                    <div className="flex items-center gap-4">
                                        <div className={`w-8 h-8 rounded-full flex items-center justify-center font-black ${index === 0 ? 'bg-amber-500 text-slate-900' : 'bg-slate-700 text-slate-300'}`}>
                                            {index + 1}
                                        </div>
                                        <span className={`font-bold text-lg ${index === 0 ? 'text-amber-400' : 'text-slate-200'}`}>
                                            {faction.class_name}
                                        </span>
                                    </div>
                                    <div className="font-black text-xl text-white text-right">
                                        {faction.total_score.toLocaleString()} <span className="text-xs font-normal text-slate-400 block -mt-1">poin total</span>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <Link
                        href={route('arena.lobby', attempt.game.id)}
                        className="flex items-center justify-center gap-2 rounded-2xl bg-slate-800 hover:bg-slate-700 border border-slate-700 text-white font-bold py-4 transition-all"
                    >
                        <RotateCcw className="h-5 w-5" /> Main Lagi
                    </Link>
                    <Link
                        href={route('dashboard')}
                        className="flex items-center justify-center gap-2 rounded-2xl bg-linear-to-r from-primary-500 to-emerald-500 hover:from-primary-400 hover:to-emerald-400 text-white font-bold py-4 transition-all shadow-lg shadow-emerald-500/25"
                    >
                        <ArrowLeft className="h-5 w-5" /> Ke Dashboard
                    </Link>
                </div>
            </div>
        </div>
    );
}
