import React, { useState } from 'react';
import { Head, usePage } from '@inertiajs/react';
import { Trophy, Flame, Target } from 'lucide-react';
import AuthenticatedLayout from '@/layouts/AuthenticatedLayout';
import type { PageProps } from '@/types';

interface ReportProps extends PageProps {
    game: {
        id: number;
        title: string;
        game_mode: string;
        classes: Array<{ id: number; name: string }>;
    };
    attempts: Array<{
        id: number;
        student: { full_name: string; synced_class: { id: number; class_name: string, name: string } };
        total_score: number;
        total_correct: number;
        total_questions: number;
        accuracy_percentage: number;
        longest_streak: number;
    }>;
    faction_leaderboard?: Array<{
        class_id: number;
        class_name: string;
        total_score: number;
    }>;
}

export default function Report() {
    const { game, attempts, faction_leaderboard } = usePage<ReportProps>().props;
    const [selectedClass, setSelectedClass] = useState<string>('all');

    const filteredAttempts = attempts.filter(attempt => {
        if (selectedClass === 'all') return true;
        return attempt.student.synced_class?.id.toString() === selectedClass;
    });

    return (
        <AuthenticatedLayout title={`Hasil Quiz: ${game.title}`} backHref="/games">
            <Head title={`Report: ${game.title}`} />

            <div className="mb-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <p className="text-sm text-text-muted">Daftar nilai tertinggi per siswa.</p>

                <div className="flex items-center gap-2 bg-surface rounded-xl p-1 border border-border/40">
                    <span className="text-sm font-medium text-text-muted pl-3">Filter Kelas:</span>
                    <select
                        aria-label="Filter berdasarkan Kelas"
                        value={selectedClass}
                        onChange={e => setSelectedClass(e.target.value)}
                        className="border-none bg-transparent text-sm font-medium focus:ring-0 text-text-light cursor-pointer"
                    >
                        <option value="all">Semua Kelas</option>
                        {game.classes?.map(c => (
                            <option key={c.id} value={c.id.toString()}>{c.name}</option>
                        ))}
                    </select>
                </div>
            </div>

            {game.game_mode === 'faction' && faction_leaderboard && (
                <div className="mb-8">
                    <h3 className="text-xl font-bold mb-4 flex items-center gap-2">
                        <Trophy className="h-6 w-6 text-blue-500" />
                        Klasemen Faction Wars
                    </h3>
                    <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                        {faction_leaderboard.map((faction, index) => (
                            <div key={faction.class_id} className={`glass rounded-2xl p-6 border relative overflow-hidden ${index === 0 ? 'border-amber-500/50' : 'border-border/40'}`}>
                                {index === 0 && (
                                    <div className="absolute -right-4 -top-4 w-16 h-16 bg-amber-500/20 blur-2xl rounded-full" />
                                )}
                                <div className="flex justify-between items-start mb-4 relative z-10">
                                    <div>
                                        <div className="text-sm font-bold text-text-muted">Peringkat #{index + 1}</div>
                                        <div className="text-xl font-black mt-1">{faction.class_name}</div>
                                    </div>
                                    {index === 0 && <Trophy className="h-8 w-8 text-amber-400" />}
                                </div>
                                <div className="relative z-10">
                                    <div className="text-sm text-text-muted mb-1">Total Energi (Skor)</div>
                                    <div className="text-3xl font-bold text-primary-400">
                                        {faction.total_score.toLocaleString()}
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            <div className="glass rounded-2xl overflow-hidden border border-border/40">
                <div className="overflow-x-auto">
                    <table className="w-full text-left text-sm text-text-muted">
                        <thead className="bg-surface-hover/30 text-xs uppercase text-text-light">
                            <tr>
                                <th className="px-6 py-4">#</th>
                                <th className="px-6 py-4">Nama Siswa</th>
                                <th className="px-6 py-4">Kelas</th>
                                <th className="px-6 py-4 text-center">Skor Akhir</th>
                                <th className="px-6 py-4 text-center">Akurasi</th>
                                <th className="px-6 py-4 text-center">Streak Terbaik</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border/40">
                            {filteredAttempts.length > 0 ? (
                                filteredAttempts.map((attempt, index) => (
                                    <tr key={attempt.id} className="hover:bg-surface-hover/20">
                                        <td className="px-6 py-4">
                                            {index === 0 ? <Trophy className="h-5 w-5 text-amber-400" /> : index + 1}
                                        </td>
                                        <td className="px-6 py-4 font-medium text-text-light">
                                            {attempt.student.full_name}
                                        </td>
                                        <td className="px-6 py-4 text-xs">
                                            <span className="bg-slate-700/50 px-2 py-1 rounded-md text-slate-300">
                                                {attempt.student.synced_class?.name || '-'}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 text-center">
                                            <span className="font-bold text-emerald-400 text-lg">
                                                {attempt.total_score.toLocaleString()}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 text-center">
                                            <div className="flex items-center justify-center gap-1 text-sky-400">
                                                <Target className="h-4 w-4" />
                                                {attempt.accuracy_percentage}%
                                            </div>
                                            <div className="text-xs text-text-muted mt-1">
                                                {attempt.total_correct}/{attempt.total_questions} Benar
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 text-center">
                                            <div className="flex items-center justify-center gap-1 text-orange-400">
                                                <Flame className="h-4 w-4" />
                                                {attempt.longest_streak}
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            ) : (
                                <tr>
                                    <td colSpan={6} className="px-6 py-12 text-center text-text-muted">
                                        Belum ada siswa yang menyelesaikan quiz ini untuk filter tersebut.
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
