import React from 'react';
import { Head, Link, usePage } from '@inertiajs/react';
import { Trophy, Target, Clock, Repeat, CheckCircle, XCircle, ArrowLeft, Globe } from 'lucide-react';
import StudentLayout from '@/layouts/StudentLayout';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';
import RichTextContent from '@/components/RichTextContent';

interface LeaderboardEntry {
    rank: number;
    student_name: string;
    grade: number;
    points: number;
    attempt_number: number;
    time_taken_seconds: number;
    is_current_user: boolean;
}

interface ReviewItem {
    question_text: string;
    selected_index: number | null;
    correct_index: number | null;
    is_correct: boolean;
    options: Array<{ text: string; is_correct?: boolean }>;
}

interface QuizResultProps extends PageProps {
    assignment: {
        id: number;
        title: string;
        material: { id: number; title: string };
    };
    bestSubmission: {
        grade: number;
        points: number;
        attempt_number: number;
        time_taken_seconds: number;
        status?: string;
        is_late?: boolean;
    } | null;
    leaderboard: LeaderboardEntry[];
    totalParticipants: number;
    averageGrade: number;
    attemptCount: number;
    maxAttempts: number;
    showReview: boolean;
    review: ReviewItem[] | null;
}

export default function QuizResult() {
    const {
        assignment,
        bestSubmission,
        leaderboard,
        totalParticipants,
        averageGrade,
        attemptCount,
        maxAttempts,
        showReview,
        review,
    } = usePage<QuizResultProps>().props;

    const formatTime = (seconds: number) => {
        const m = Math.floor(seconds / 60);
        const s = seconds % 60;
        return `${m}m ${s}s`;
    };

    const getRankBadge = (rank: number) => {
        if (rank === 1) return 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30';
        if (rank === 2) return 'bg-slate-400/20 text-slate-300 border-slate-400/30';
        if (rank === 3) return 'bg-amber-700/20 text-amber-600 border-amber-700/30';
        return 'bg-surface border-border/50 text-text-muted';
    };

    return (
        <>
            <Head title={`Hasil: ${assignment.title}`} />

            <div className="mx-auto max-w-4xl space-y-6">
                {/* Back */}
                <Link
                    href={`/materials/${assignment.material.id}`}
                    className="inline-flex items-center gap-1 text-sm text-text-muted hover:text-text transition-colors"
                >
                    <ArrowLeft className="h-4 w-4" /> Kembali ke Materi
                </Link>

                {/* Score Card */}
                {bestSubmission && (
                    <div className="glass rounded-2xl p-8 border border-border/40 text-center">
                        <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-emerald-500/20 mb-4">
                            <Trophy className="h-10 w-10 text-emerald-400" />
                        </div>
                        <h1 className="text-3xl font-black text-text-light">{bestSubmission.grade}%</h1>
                        <p className="text-text-muted mt-1">Skor Terbaik</p>

                        <div className="grid grid-cols-3 gap-4 mt-6">
                            <div className="bg-surface rounded-xl p-4">
                                <Target className="h-5 w-5 text-emerald-400 mx-auto mb-1" />
                                <p className="text-lg font-bold text-text-light">{bestSubmission.points.toLocaleString()}</p>
                                <p className="text-xs text-text-muted">Poin</p>
                            </div>
                            <div className="bg-surface rounded-xl p-4">
                                <Repeat className="h-5 w-5 text-sky-400 mx-auto mb-1" />
                                <p className="text-lg font-bold text-text-light">{bestSubmission.attempt_number}</p>
                                <p className="text-xs text-text-muted">Attempt</p>
                            </div>
                            <div className="bg-surface rounded-xl p-4">
                                <Clock className="h-5 w-5 text-amber-400 mx-auto mb-1" />
                                <p className="text-lg font-bold text-text-light">{formatTime(bestSubmission.time_taken_seconds)}</p>
                                <p className="text-xs text-text-muted">Waktu</p>
                            </div>
                        </div>

                        <p className="text-sm text-text-muted mt-4">
                            Attempt {attemptCount} dari {maxAttempts} digunakan
                        </p>

                        {bestSubmission.is_late && (
                            <p className="mt-2 text-xs font-bold text-rose-400">Dikirim setelah tenggat waktu (terlambat)</p>
                        )}

                        {attemptCount < maxAttempts && (
                            <Link
                                href={route('quiz.start', assignment.id)}
                                className="inline-flex items-center gap-2 mt-4 px-6 py-2 rounded-xl bg-emerald-500 text-white font-bold hover:bg-emerald-400 transition-all"
                            >
                                <Repeat className="h-4 w-4" />
                                Coba Lagi ({maxAttempts - attemptCount} attempt tersisa)
                            </Link>
                        )}
                    </div>
                )}

                {/* Leaderboard */}
                <div className="glass rounded-2xl border border-border/40 overflow-hidden">
                    <div className="p-6 border-b border-border/40">
                        <h2 className="text-lg font-bold text-text-light flex items-center gap-2">
                            <Trophy className="h-5 w-5 text-yellow-400" />
                            Leaderboard
                        </h2>
                        <p className="text-sm text-text-muted mt-1">
                            {totalParticipants} peserta &bull; Rata-rata: {averageGrade}%
                        </p>
                    </div>
                    <div className="divide-y divide-border/40">
                        {leaderboard.length > 0 ? (
                            leaderboard.map((entry) => (
                                <div
                                    key={entry.rank}
                                    className={cn(
                                        'flex items-center gap-4 px-6 py-3',
                                        entry.is_current_user && 'bg-emerald-500/5'
                                    )}
                                >
                                    <div
                                        className={cn(
                                            'w-8 h-8 rounded-full border flex items-center justify-center text-xs font-bold shrink-0',
                                            getRankBadge(entry.rank)
                                        )}
                                    >
                                        {entry.rank}
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <p className={cn('text-sm font-medium truncate', entry.is_current_user ? 'text-emerald-400' : 'text-text-light')}>
                                            {entry.student_name}
                                            {entry.is_current_user && <span className="ml-2 text-xs text-emerald-500">(Kamu)</span>}
                                        </p>
                                        <p className="text-xs text-text-muted">
                                            Attempt {entry.attempt_number} &bull; {formatTime(entry.time_taken_seconds)}
                                        </p>
                                    </div>
                                    <div className="text-right">
                                        <p className="text-sm font-bold text-text-light">{entry.grade}%</p>
                                        <p className="text-xs text-emerald-400">{entry.points.toLocaleString()} poin</p>
                                    </div>
                                </div>
                            ))
                        ) : (
                            <div className="px-6 py-8 text-center text-text-muted text-sm">
                                Belum ada peserta.
                            </div>
                        )}
                    </div>
                </div>

                {/* Review (setelah semua attempt habis) */}
                {showReview && review && (
                    <div className="glass rounded-2xl border border-border/40 overflow-hidden">
                        <div className="p-6 border-b border-border/40">
                            <h2 className="text-lg font-bold text-text-light">Pembahasan</h2>
                            <p className="text-sm text-text-muted mt-1">Semua attempt sudah digunakan</p>
                        </div>
                        <div className="divide-y divide-border/40">
                            {review.map((item, idx) => (
                                <div key={idx} className="p-6">
                                    <div className="flex items-start gap-3">
                                        {item.is_correct ? (
                                            <CheckCircle className="h-5 w-5 text-emerald-400 shrink-0 mt-0.5" />
                                        ) : (
                                            <XCircle className="h-5 w-5 text-rose-400 shrink-0 mt-0.5" />
                                        )}
                                        <div>
                                            <RichTextContent html={item.question_text} className="text-sm font-medium text-text-light" />
                                            <div className="mt-2 space-y-1">
                                                {item.options.map((opt, optIdx) => (
                                                    <p
                                                        key={optIdx}
                                                        className={cn(
                                                            'text-xs px-2 py-1 rounded',
                                                            optIdx === item.correct_index
                                                                ? 'bg-emerald-500/10 text-emerald-400'
                                                                : optIdx === item.selected_index && !item.is_correct
                                                                ? 'bg-rose-500/10 text-rose-400'
                                                                : 'text-text-muted'
                                                        )}
                                                    >
                                                        {optIdx === item.selected_index && !item.is_correct && '✗ '}
                                                        {optIdx === item.correct_index && '✓ '}
                                                        {opt.text}
                                                    </p>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Global Leaderboard Link */}
                <div className="text-center">
                    <Link
                        href={route('quiz.leaderboard.global')}
                        className="inline-flex items-center gap-2 text-sm text-emerald-400 hover:text-emerald-300 transition-colors"
                    >
                        <Globe className="h-4 w-4" />
                        Lihat Leaderboard Global
                    </Link>
                </div>
            </div>
        </>
    );
}

QuizResult.layout = (page: any) => <StudentLayout title="Hasil Quiz">{page}</StudentLayout>;
