import { Form, Head, Link, router } from '@inertiajs/react';
import {
    CheckCircle2,
    Clock,
    XCircle,
    BookOpen,
    Play,
    FileText,
    ClipboardList,
    ChevronDown,
    ChevronLeft,
    ChevronRight,
    Circle
} from 'lucide-react';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type Option = { text: string; is_correct: boolean };
type Question = {
    id: number;
    type: 'multiple_choice' | 'true_false' | 'essay';
    question: string;
    options: Option[] | null;
    correct_answer: string | null;
    points: number;
    order: number;
};

type Quiz = {
    id: number;
    chapter_id: number;
    title: string;
    description: string | null;
    duration_minutes: number;
    passing_score: number;
    max_attempts: number;
    questions: Question[];
    deadline: string | null;
};

type Answer = { id: number; answer: string; is_correct: boolean | null; points_earned: number | null; question: Question };
type Attempt = { id: number; score: number | null; passed: boolean | null; status: string; answers: Answer[] } | null;
type ActiveAttempt = { id: number; started_at: string } | null;

type SimpleLesson = { id: number; title: string; type: string; order: number };
type SimpleQuiz = { id: number; title: string; order: number };
type SimpleAssignment = { id: number; title: string; order: number };
type Chapter = {
    id: number;
    title: string;
    order: number;
    lessons: SimpleLesson[];
    quizzes: SimpleQuiz[];
    assignments: SimpleAssignment[];
};

type Props = {
    course: { id: number; title: string; slug: string; chapters: Chapter[] };
    quiz: Quiz;
    attemptCount: number;
    lastAttempt: Attempt;
    activeAttempt: ActiveAttempt;
    canAttempt: boolean;
    completedLessonIds: number[];
    progress: { total: number; completed: number; percent: number };
    prev_item: { id: number; type: string; url: string } | null;
    next_item: { id: number; type: string; url: string } | null;
};

const BRAND = '#118AB2';
const SUCCESS = '#06D6A0';

function lessonTypeIcon(type: string) {
    if (type === 'video') return <Play className="h-3.5 w-3.5" />;
    if (type === 'pdf' || type === 'file') return <FileText className="h-3.5 w-3.5" />;
    return <BookOpen className="h-3.5 w-3.5" />;
}

export default function QuizShow({
    course,
    quiz,
    attemptCount,
    lastAttempt,
    activeAttempt,
    canAttempt,
    completedLessonIds,
    progress,
    prev_item,
    next_item,
}: Props) {
    const [isStarted, setIsStarted] = useState(!!activeAttempt);
    const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
    const [answers, setAnswers] = useState<Record<number, string>>({});
    const [openChapters, setOpenChapters] = useState<Record<number, boolean>>({
        [quiz.chapter_id]: true
    });
    const [timeLeft, setTimeLeft] = useState<number>(0);
    const [showConfirmModal, setShowConfirmModal] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);

    const confirmAndSubmit = () => {
        const form = document.getElementById('quiz-form') as HTMLFormElement;
        if (form) {
            setIsSubmitting(true);
            const formData = new FormData(form);
            router.post(form.action, formData, {
                onFinish: () => {
                    setIsSubmitting(false);
                    setShowConfirmModal(false);
                    setIsStarted(false);
                }
            });
        }
    };

    useEffect(() => {
        if (!isStarted || !activeAttempt) return;

        const startTime = new Date(activeAttempt.started_at).getTime();
        const durationMs = quiz.duration_minutes * 60 * 1000;
        const endTime = startTime + durationMs;

        const updateTimer = () => {
            const now = new Date().getTime();
            const diff = endTime - now;
            if (diff <= 0) {
                setTimeLeft(0);
                // Submit form automatically
                const form = document.querySelector('form');
                if (form) {
                    router.post(form.action, new FormData(form), {
                        onSuccess: () => setIsStarted(false),
                    });
                }
            } else {
                setTimeLeft(Math.floor(diff / 1000));
            }
        };

        updateTimer();
        const interval = setInterval(updateTimer, 1000);
        return () => clearInterval(interval);
    }, [isStarted, activeAttempt, quiz.duration_minutes]);

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

    function startQuiz() {
        router.post(`/courses/${course.slug}/quiz/${quiz.id}/start`, {}, {
            onSuccess: () => setIsStarted(true),
        });
    }

    return (
        <>
            <Head title={`${quiz.title} — ${course.title}`} />

            <div className="flex h-[calc(100vh-64px)]" style={{ backgroundColor: '#F5F6F8' }}>

                {/* ── SIDEBAR ────────────────────────────────────────────── */}
                <aside
                    className="hidden lg:flex flex-col shrink-0 overflow-hidden"
                    style={{
                        width: 292,
                        backgroundColor: '#FFFFFF',
                        borderRight: '1px solid rgba(0,0,0,0.08)',
                    }}
                >
                    {/* Course header */}
                    <div className="shrink-0 p-4" style={{ borderBottom: '1px solid rgba(0,0,0,0.07)' }}>
                        <Link
                            href={`/my-courses/${course.slug}`}
                            className="mb-3 inline-flex items-center gap-1 text-xs transition-colors"
                            style={{ color: '#AAAAAA' }}
                            onMouseEnter={(e) => (e.currentTarget.style.color = BRAND)}
                            onMouseLeave={(e) => (e.currentTarget.style.color = '#AAAAAA')}
                        >
                            <ChevronLeft className="h-3 w-3" />
                            Kelas Saya
                        </Link>

                        <p className="text-base font-semibold leading-snug" style={{ color: '#1A1A1A' }}>
                            {course.title}
                        </p>

                        <div className="mt-3">
                            <div className="mb-1.5 flex items-center justify-between text-sm" style={{ color: '#BBBBBB' }}>
                                <span>{progress.completed}/{progress.total} materi selesai</span>
                                <span className="font-semibold" style={{ color: BRAND }}>{progress.percent}%</span>
                            </div>
                            <div className="h-1.5 overflow-hidden rounded-full" style={{ backgroundColor: 'rgba(0,0,0,0.07)' }}>
                                <div
                                    className="h-full rounded-full transition-all duration-500"
                                    style={{ width: `${progress.percent}%`, backgroundColor: BRAND }}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Chapter list */}
                    <div className="flex-1 overflow-y-auto">
                        {course.chapters.map((chapter, idx) => {
                            const isOpen = !!openChapters[chapter.id];
                            const hasActiveQuiz = chapter.quizzes.some((q) => q.id === quiz.id);

                            return (
                                <div key={chapter.id} style={{ borderBottom: '1px solid rgba(0,0,0,0.05)' }}>
                                    {/* Chapter header */}
                                    <button
                                        onClick={() => setOpenChapters(prev => ({ ...prev, [chapter.id]: !prev[chapter.id] }))}
                                        className="flex w-full items-center gap-2.5 px-4 py-3 text-left transition-colors"
                                        style={{
                                            backgroundColor: isOpen ? 'rgba(17,138,178,0.03)' : 'transparent',
                                        }}
                                    >
                                        <span
                                            className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold"
                                            style={
                                                hasActiveQuiz
                                                    ? { backgroundColor: BRAND, color: '#FFFFFF' }
                                                    : { backgroundColor: 'rgba(0,0,0,0.08)', color: '#888888' }
                                            }
                                        >
                                            {idx + 1}
                                        </span>
                                        <span className="flex-1 text-sm font-semibold leading-snug" style={{ color: '#2A2A2A' }}>
                                            {chapter.title}
                                        </span>
                                        <ChevronDown
                                            className="h-3.5 w-3.5 shrink-0 transition-transform"
                                            style={{
                                                color: '#CCCCCC',
                                                transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                                            }}
                                        />
                                    </button>

                                    {/* Lesson / quiz / assignment items */}
                                    {isOpen && (
                                        <div style={{ backgroundColor: 'rgba(0,0,0,0.01)' }}>
                                            {chapter.lessons.map((l) => {
                                                const done = completedLessonIds.includes(l.id);
                                                return (
                                                    <Link
                                                        key={l.id}
                                                        href={`/courses/${course.slug}/learn/${l.id}`}
                                                        className="flex items-center gap-2.5 py-2.5 pr-4 transition-colors"
                                                        style={{
                                                            paddingLeft: 16,
                                                            borderLeft: '3px solid transparent',
                                                            backgroundColor: 'transparent',
                                                        }}
                                                        onMouseEnter={(e) => {
                                                            e.currentTarget.style.backgroundColor = 'rgba(0,0,0,0.03)';
                                                        }}
                                                        onMouseLeave={(e) => {
                                                            e.currentTarget.style.backgroundColor = 'transparent';
                                                        }}
                                                    >
                                                        <span
                                                            className="shrink-0"
                                                            style={{ color: done ? SUCCESS : '#CCCCCC' }}
                                                        >
                                                            {done ? <CheckCircle2 className="h-3.5 w-3.5" /> : lessonTypeIcon(l.type)}
                                                        </span>
                                                        <span
                                                            className="line-clamp-2 text-sm leading-snug"
                                                            style={{
                                                                color: done ? '#BBBBBB' : '#555555',
                                                                textDecoration: done ? 'line-through' : 'none',
                                                            }}
                                                        >
                                                            {l.title}
                                                        </span>
                                                    </Link>
                                                );
                                            })}

                                            {chapter.quizzes.map((q) => {
                                                const active = q.id === quiz.id;
                                                return (
                                                    <Link
                                                        key={`q-${q.id}`}
                                                        href={`/courses/${course.slug}/quiz/${q.id}`}
                                                        className="flex items-center gap-2.5 py-2.5 pr-4 transition-colors"
                                                        style={{
                                                            paddingLeft: active ? 13 : 16,
                                                            borderLeft: `3px solid ${active ? BRAND : 'transparent'}`,
                                                            backgroundColor: active ? 'rgba(17,138,178,0.06)' : 'transparent',
                                                        }}
                                                        onMouseEnter={(e) => {
                                                            if (!active) e.currentTarget.style.backgroundColor = 'rgba(255,183,3,0.06)';
                                                        }}
                                                        onMouseLeave={(e) => {
                                                            if (!active) e.currentTarget.style.backgroundColor = 'transparent';
                                                        }}
                                                    >
                                                        <ClipboardList className="h-3.5 w-3.5 shrink-0" style={{ color: active ? BRAND : '#D4A000' }} />
                                                        <span
                                                            className="line-clamp-2 text-sm leading-snug"
                                                            style={{
                                                                color: active ? BRAND : '#555555',
                                                                fontWeight: active ? 600 : 400,
                                                            }}
                                                        >
                                                            {q.title}
                                                        </span>
                                                    </Link>
                                                );
                                            })}

                                            {chapter.assignments.map((a) => (
                                                <Link
                                                    key={`a-${a.id}`}
                                                    href={`/courses/${course.slug}/assignment/${a.id}`}
                                                    className="flex items-center gap-2.5 px-4 py-2.5 transition-colors"
                                                    onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = 'rgba(99,102,241,0.06)')}
                                                    onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
                                                >
                                                    <FileText className="h-3.5 w-3.5 shrink-0" style={{ color: '#6366F1' }} />
                                                    <span className="line-clamp-2 text-sm leading-snug" style={{ color: '#555555' }}>
                                                        {a.title}
                                                    </span>
                                                </Link>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </aside>

                {/* ── MAIN CONTENT ───────────────────────────────────────── */}
                <main className="flex flex-1 flex-col overflow-hidden">
                    <div className="flex-1 overflow-y-auto">
                        <div className={`mx-auto px-5 py-8 transition-all duration-300 ${isStarted ? 'max-w-5xl' : 'max-w-3xl'}`}>

                            {/* Header / Meta Card */}
                            <div
                                className="mb-6 rounded-2xl bg-white p-6"
                                style={{
                                    border: '1px solid rgba(0,0,0,0.07)',
                                    boxShadow: '0 2px 12px rgba(0,0,0,0.04)',
                                }}
                            >
                                <h1 className="text-xl font-bold leading-snug" style={{ color: '#1A1A1A' }}>
                                    {quiz.title}
                                </h1>
                                {quiz.description && (
                                    <p className="mt-2 text-sm text-gray-500 leading-relaxed">{quiz.description}</p>
                                )}
                                <div className="mt-4 flex flex-wrap gap-3 text-sm">
                                    {isStarted ? (
                                        <span
                                            className="inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-xs font-bold animate-pulse"
                                            style={{
                                                color: timeLeft < 120 ? '#EF476F' : BRAND,
                                                backgroundColor: timeLeft < 120 ? 'rgba(239,71,111,0.08)' : 'rgba(17,138,178,0.08)',
                                                border: `1px solid ${timeLeft < 120 ? 'rgba(239,71,111,0.15)' : 'rgba(17,138,178,0.15)'}`,
                                            }}
                                        >
                                            <Clock className="h-4 w-4" />
                                            Sisa Waktu: {formatTime(timeLeft)}
                                        </span>
                                    ) : (
                                        <span className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1 text-xs font-semibold" style={{ color: BRAND, backgroundColor: 'rgba(17,138,178,0.08)' }}>
                                            <Clock className="h-3.5 w-3.5" />
                                            {quiz.duration_minutes} menit
                                        </span>
                                    )}
                                    <span className="inline-flex items-center gap-1 rounded-lg bg-gray-100 px-2.5 py-1 text-xs font-semibold text-gray-600">
                                        {quiz.questions.length} Soal
                                    </span>
                                    <span className="inline-flex items-center gap-1 rounded-lg bg-gray-100 px-2.5 py-1 text-xs font-semibold text-gray-600">
                                        Nilai kelulusan: {quiz.passing_score}
                                    </span>
                                    <span className="inline-flex items-center gap-1 rounded-lg bg-gray-100 px-2.5 py-1 text-xs font-semibold text-gray-600">
                                        Percobaan: {attemptCount}/{quiz.max_attempts}
                                    </span>
                                </div>
                            </div>

                            {/* Last Attempt Result Badge */}
                            {lastAttempt && !isStarted && (
                                <div
                                    className="mb-6 rounded-2xl p-5 flex items-center gap-4"
                                    style={{
                                        border: `1px solid ${lastAttempt.passed ? 'rgba(6,214,160,0.2)' : 'rgba(239,71,111,0.2)'}`,
                                        backgroundColor: lastAttempt.passed ? 'rgba(6,214,160,0.04)' : 'rgba(239,71,111,0.04)',
                                    }}
                                >
                                    {lastAttempt.passed ? (
                                        <CheckCircle2 className="h-6 w-6 text-green-500 shrink-0" />
                                    ) : (
                                        <XCircle className="h-6 w-6 text-red-500 shrink-0" />
                                    )}
                                    <div>
                                        <p className="text-sm font-semibold" style={{ color: lastAttempt.passed ? SUCCESS : '#EF476F' }}>
                                            {lastAttempt.status === 'submitted'
                                                ? 'Menunggu Penilaian Essay'
                                                : lastAttempt.passed
                                                  ? 'Selamat! Kamu Lulus'
                                                  : 'Maaf, Kamu Belum Lulus'}
                                        </p>
                                        {lastAttempt.score !== null && (
                                            <p className="text-xs text-gray-500 mt-0.5">Nilai akhir: <strong className="text-sm text-gray-700">{lastAttempt.score}</strong></p>
                                        )}
                                    </div>
                                </div>
                            )}

                            {/* Quiz / Start Panel */}
                            {isStarted ? (
                                <Form
                                    id="quiz-form"
                                    action={`/courses/${course.slug}/quiz/${quiz.id}/submit`}
                                    method="post"
                                    className="flex flex-col gap-6"
                                >
                                    {({ processing }) => (
                                        <div className="grid grid-cols-1 md:grid-cols-12 gap-6">
                                            {/* Left Column: Question & Navigation Card (8 cols) */}
                                            <div className="md:col-span-8 flex flex-col gap-6">
                                                {quiz.questions.map((q, index) => (
                                                    <div
                                                        key={q.id}
                                                        className={`rounded-2xl bg-white p-6 ${index === currentQuestionIndex ? 'block' : 'hidden'}`}
                                                        style={{
                                                            border: '1px solid rgba(0,0,0,0.07)',
                                                            boxShadow: '0 2px 12px rgba(0,0,0,0.04)',
                                                        }}
                                                    >
                                                        <p className="mb-4 text-base font-semibold leading-relaxed" style={{ color: '#1A1A1A' }}>
                                                            <span className="mr-1.5 text-gray-400">{index + 1}.</span>
                                                            {q.question}
                                                        </p>

                                                        {q.type === 'multiple_choice' && q.options && (
                                                            <div className="space-y-2.5">
                                                                {q.options.map((opt, i) => (
                                                                    <label
                                                                        key={i}
                                                                        className="flex cursor-pointer items-center gap-3 rounded-xl border p-3.5 hover:bg-slate-50 transition-colors"
                                                                        style={{ borderColor: 'rgba(0,0,0,0.08)' }}
                                                                    >
                                                                        <input
                                                                            type="radio"
                                                                            name={`answers[${q.id}]`}
                                                                            value={opt.text}
                                                                            checked={answers[q.id] === opt.text}
                                                                            onChange={(e) => setAnswers(prev => ({ ...prev, [q.id]: e.target.value }))}
                                                                            className="shrink-0"
                                                                            style={{ accentColor: BRAND }}
                                                                        />
                                                                        <span className="text-sm text-gray-700 font-medium">{opt.text}</span>
                                                                    </label>
                                                                ))}
                                                            </div>
                                                        )}

                                                        {q.type === 'true_false' && (
                                                            <div className="flex gap-4">
                                                                {['true', 'false'].map((val) => (
                                                                    <label
                                                                        key={val}
                                                                        className="flex flex-1 cursor-pointer items-center justify-center gap-2 rounded-xl border p-3.5 hover:bg-slate-50 transition-colors"
                                                                        style={{ borderColor: 'rgba(0,0,0,0.08)' }}
                                                                    >
                                                                        <input
                                                                            type="radio"
                                                                            name={`answers[${q.id}]`}
                                                                            value={val}
                                                                            checked={answers[q.id] === val}
                                                                            onChange={(e) => setAnswers(prev => ({ ...prev, [q.id]: e.target.value }))}
                                                                            style={{ accentColor: BRAND }}
                                                                        />
                                                                        <span className="text-sm font-semibold text-gray-700">
                                                                            {val === 'true' ? 'Benar' : 'Salah'}
                                                                        </span>
                                                                    </label>
                                                                ))}
                                                            </div>
                                                        )}

                                                        {q.type === 'essay' && (
                                                            <textarea
                                                                name={`answers[${q.id}]`}
                                                                rows={4}
                                                                placeholder="Tulis jawabanmu di sini..."
                                                                value={answers[q.id] || ''}
                                                                onChange={(e) => setAnswers(prev => ({ ...prev, [q.id]: e.target.value }))}
                                                                className="w-full rounded-xl border bg-slate-50 p-3.5 text-sm outline-none transition-colors focus:border-cyan-500"
                                                                style={{ borderColor: 'rgba(0,0,0,0.12)' }}
                                                            />
                                                        )}
                                                    </div>
                                                ))}

                                                {/* Navigation controls under active question */}
                                                <div className="rounded-2xl bg-white p-5 flex items-center justify-between border" style={{ borderColor: 'rgba(0,0,0,0.07)' }}>
                                                    <div className="w-1/4 flex justify-start">
                                                        {currentQuestionIndex > 0 ? (
                                                            <button
                                                                type="button"
                                                                onClick={() => setCurrentQuestionIndex(prev => prev - 1)}
                                                                className="inline-flex items-center gap-1.5 rounded-xl border px-4 py-2 text-sm font-semibold text-gray-600 bg-white transition-all hover:bg-gray-50 hover:-translate-y-0.5 active:translate-y-0"
                                                                style={{ borderColor: 'rgba(0,0,0,0.08)' }}
                                                            >
                                                                <ChevronLeft className="h-4 w-4" />
                                                                Sebelumnya
                                                            </button>
                                                        ) : (
                                                            <div />
                                                        )}
                                                    </div>

                                                    <span className="text-sm font-medium text-gray-500">
                                                        Soal {currentQuestionIndex + 1} dari {quiz.questions.length}
                                                    </span>

                                                    <div className="w-1/4 flex justify-end">
                                                        {currentQuestionIndex < quiz.questions.length - 1 ? (
                                                            <button
                                                                key="next-btn"
                                                                type="button"
                                                                onClick={() => setCurrentQuestionIndex(prev => prev + 1)}
                                                                className="inline-flex items-center gap-1.5 rounded-xl border px-4 py-2 text-sm font-semibold transition-all hover:-translate-y-0.5 active:translate-y-0"
                                                                style={{
                                                                    borderColor: BRAND,
                                                                    color: BRAND,
                                                                    backgroundColor: '#FFFFFF',
                                                                }}
                                                                onMouseEnter={(e) => {
                                                                    e.currentTarget.style.backgroundColor = 'rgba(17,138,178,0.04)';
                                                                }}
                                                                onMouseLeave={(e) => {
                                                                    e.currentTarget.style.backgroundColor = '#FFFFFF';
                                                                }}
                                                            >
                                                                Selanjutnya
                                                                <ChevronRight className="h-4 w-4" />
                                                            </button>
                                                        ) : (
                                                        <button
                                                                key="submit-btn"
                                                                type="button"
                                                                onClick={() => setShowConfirmModal(true)}
                                                                disabled={processing || isSubmitting}
                                                                className="inline-flex items-center justify-center gap-2 rounded-xl px-5 py-2 text-sm font-semibold text-white transition-all hover:-translate-y-0.5 active:translate-y-0 animate-pulse"
                                                                style={{
                                                                    backgroundColor: BRAND,
                                                                    boxShadow: '0 4px 14px rgba(17,138,178,0.3)',
                                                                }}
                                                            >
                                                                {(processing || isSubmitting) && <Spinner className="h-4 w-4" />}
                                                                Kumpulkan Kuis
                                                            </button>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>

                                            {/* Right Column: Numbers grid (4 cols) */}
                                            <div className="md:col-span-4">
                                                <div
                                                    className="rounded-2xl bg-white p-5 border sticky top-20"
                                                    style={{ borderColor: 'rgba(0,0,0,0.07)' }}
                                                >
                                                    <h3 className="text-sm font-semibold mb-4 text-gray-700">Daftar Soal</h3>
                                                    <div className="flex flex-wrap gap-2">
                                                        {quiz.questions.map((q, index) => {
                                                            const isActive = index === currentQuestionIndex;
                                                            const hasAnswer = answers[q.id] !== undefined && answers[q.id].trim() !== '';

                                                            return (
                                                                <button
                                                                    key={q.id}
                                                                    type="button"
                                                                    onClick={() => setCurrentQuestionIndex(index)}
                                                                    className="flex h-10 w-10 items-center justify-center rounded-xl text-sm font-bold border transition-all hover:-translate-y-0.5 active:translate-y-0"
                                                                    style={{
                                                                        borderColor: isActive ? BRAND : hasAnswer ? SUCCESS : 'rgba(0,0,0,0.08)',
                                                                        backgroundColor: isActive ? BRAND : hasAnswer ? 'rgba(6,214,160,0.1)' : '#FFFFFF',
                                                                        color: isActive ? '#FFFFFF' : hasAnswer ? SUCCESS : '#555555',
                                                                    }}
                                                                >
                                                                    {index + 1}
                                                                </button>
                                                            );
                                                        })}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                </Form>
                            ) : (
                                <div
                                    className="rounded-2xl bg-white p-8 text-center"
                                    style={{
                                        border: '1px solid rgba(0,0,0,0.07)',
                                        boxShadow: '0 2px 12px rgba(0,0,0,0.04)',
                                    }}
                                >
                                    {canAttempt ? (
                                        <>
                                            <p className="mb-5 text-sm text-gray-600 leading-relaxed">
                                                Kamu akan mengerjakan <strong>{quiz.questions.length} soal</strong> dalam waktu{' '}
                                                <strong>{quiz.duration_minutes} menit</strong>.
                                            </p>
                                            <button
                                                onClick={startQuiz}
                                                className="inline-flex items-center gap-2 rounded-xl px-6 py-2.5 text-sm font-semibold text-white transition-all hover:-translate-y-0.5 active:translate-y-0"
                                                style={{
                                                    backgroundColor: BRAND,
                                                    boxShadow: '0 4px 14px rgba(17,138,178,0.3)',
                                                }}
                                            >
                                                Mulai Quiz
                                            </button>
                                        </>
                                    ) : (
                                        <p className="text-sm text-gray-500">
                                            Kamu sudah mencapai batas maksimal percobaan ({quiz.max_attempts}x).
                                        </p>
                                    )}
                                </div>
                            )}

                            {/* Navigation & Controls */}
                            {!isStarted && (
                                <div className="mt-8 flex items-center justify-between border-t pt-6" style={{ borderColor: 'rgba(0,0,0,0.08)' }}>
                                    {/* Left: Prev button */}
                                    <div className="w-1/4 flex justify-start">
                                        {prev_item ? (
                                            <Link
                                                href={prev_item.url}
                                                className="inline-flex items-center gap-1.5 rounded-xl border px-4 py-2 text-sm font-semibold text-gray-600 transition-all hover:bg-gray-50 hover:-translate-y-0.5 active:translate-y-0"
                                                style={{ borderColor: 'rgba(0,0,0,0.08)', backgroundColor: '#FFFFFF' }}
                                            >
                                                <ChevronLeft className="h-4 w-4" />
                                                Sebelumnya
                                            </Link>
                                        ) : (
                                            <div />
                                        )}
                                    </div>

                                    <div className="flex items-center gap-3 justify-center">
                                        {lastAttempt && (
                                            <span
                                                className="inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-semibold"
                                                style={
                                                    lastAttempt.passed
                                                        ? { backgroundColor: 'rgba(6,214,160,0.12)', color: SUCCESS }
                                                        : { backgroundColor: 'rgba(239,71,111,0.12)', color: '#EF476F' }
                                                }
                                            >
                                                {lastAttempt.passed ? 'Lulus' : 'Belum Lulus'}
                                            </span>
                                        )}
                                    </div>

                                    {/* Right: Next button */}
                                    <div className="w-1/4 flex justify-end">
                                        {next_item ? (
                                            <Link
                                                href={next_item.url}
                                                className="inline-flex items-center gap-1.5 rounded-xl border px-4 py-2 text-sm font-semibold transition-all hover:-translate-y-0.5 active:translate-y-0"
                                                style={{
                                                    borderColor: BRAND,
                                                    color: BRAND,
                                                    backgroundColor: '#FFFFFF',
                                                }}
                                                onMouseEnter={(e) => {
                                                    e.currentTarget.style.backgroundColor = 'rgba(17,138,178,0.04)';
                                                }}
                                                onMouseLeave={(e) => {
                                                    e.currentTarget.style.backgroundColor = '#FFFFFF';
                                                }}
                                            >
                                                Berikutnya
                                                <ChevronRight className="h-4 w-4" />
                                            </Link>
                                        ) : (
                                            <div />
                                        )}
                                    </div>
                                </div>
                            )}

                        </div>
                    </div>
                </main>

            </div>

            {/* Custom Premium Confirmation Modal */}
            {showConfirmModal && (
                <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
                    {/* Backdrop */}
                    <div 
                        className="fixed inset-0 bg-black/40 backdrop-blur-sm"
                        onClick={() => setShowConfirmModal(false)}
                    />
                    
                    {/* Modal Card */}
                    <div 
                        className="relative w-full max-w-md rounded-2xl bg-white p-6 shadow-2xl animate-in fade-in zoom-in-95 duration-200"
                        style={{ border: '1px solid rgba(0,0,0,0.08)' }}
                    >
                        <h3 className="text-lg font-bold text-gray-900 mb-2">Kumpulkan Kuis?</h3>
                        
                        <p className="text-sm text-gray-500 leading-relaxed mb-6">
                            {(() => {
                                const answeredCount = Object.keys(answers).filter(
                                    key => answers[Number(key)] !== undefined && answers[Number(key)].trim() !== ''
                                ).length;
                                const unanswered = quiz.questions.length - answeredCount;
                                
                                if (unanswered > 0) {
                                    return (
                                        <span className="text-red-500 font-medium">
                                            Perhatian: Anda baru menjawab {answeredCount} dari {quiz.questions.length} soal. Masih ada {unanswered} soal yang belum dijawab. Apakah Anda yakin tetap ingin mengumpulkan?
                                        </span>
                                    );
                                }
                                return `Anda telah menjawab seluruh ${quiz.questions.length} soal dengan lengkap. Apakah Anda yakin ingin mengumpulkan kuis sekarang?`;
                            })()}
                        </p>

                        <div className="flex items-center justify-end gap-3">
                            <button
                                type="button"
                                onClick={() => setShowConfirmModal(false)}
                                disabled={isSubmitting}
                                className="rounded-xl px-4 py-2 text-sm font-semibold text-gray-600 border bg-white hover:bg-gray-50 transition-colors"
                                style={{ borderColor: 'rgba(0,0,0,0.08)' }}
                            >
                                Batal
                            </button>
                            <button
                                type="button"
                                onClick={confirmAndSubmit}
                                disabled={isSubmitting}
                                className="inline-flex items-center gap-2 rounded-xl px-5 py-2 text-sm font-semibold text-white transition-all hover:bg-opacity-95"
                                style={{
                                    backgroundColor: BRAND,
                                    boxShadow: '0 4px 14px rgba(17,138,178,0.2)'
                                }}
                            >
                                {isSubmitting && <Spinner className="h-4 w-4" />}
                                Ya, Kumpulkan
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
}

QuizShow.layout = (page: React.ReactNode) => {
    const props = (page as React.ReactElement)?.props as Props | undefined;
    const breadcrumbs: BreadcrumbItem[] = props?.course
        ? [
              { title: 'Kelas Saya', href: '/my-courses' },
              { title: props.course.title, href: `/my-courses/${props.course.slug}` },
              { title: props.quiz.title, href: '#' },
          ]
        : [];
    return <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>;
};
