import { Head, Link, useForm, router } from '@inertiajs/react'; // <-- Menambahkan 'router' di sini
import {
    Activity, ClipboardCheck, Home, User, LogOut, Plus,
    ChevronRight, ChevronLeft, CheckCircle2, ShieldCheck, AlertTriangle, HelpCircle
} from 'lucide-react';
import { useState } from 'react';

// PERHATIKAN: Kita menangkap props `questions` dari controller Laravel
export default function Kuis({ auth = {}, questions = [] }) {
    const [showProfileMenu, setShowProfileMenu] = useState(false);
    const [currentIndex, setCurrentIndex] = useState(0);
    const [answers, setAnswers] = useState({});
    const [isFinished, setIsFinished] = useState(false);

    const { post, processing } = useForm({});

    const currentQuestion = questions[currentIndex];

    // Cegah error jika tidak ada pertanyaan
    const totalQuestions = questions.length;
    const progress = totalQuestions > 0 ? ((currentIndex) / totalQuestions) * 100 : 0;

    const handleSelectOption = (optionScore, optionText) => {
        setAnswers({ ...answers, [currentQuestion.id]: { score: Number(optionScore), text: optionText } });
    };

    const handleNext = () => {
        if (currentIndex < totalQuestions - 1) {
            setCurrentIndex(currentIndex + 1);
        } else {
            setIsFinished(true);
        }
    };

    const handlePrev = () => { if (currentIndex > 0) setCurrentIndex(currentIndex - 1); };

    // Logika perhitungan skor baru (Dinamis berdasarkan persentase)
    const renderResult = () => {
        let totalScore = 0;
        let maxPossibleScore = 0;

        // 1. Hitung poin maksimal yang bisa didapat dari seluruh soal
        questions.forEach(q => {
            const maxScoreForThisQuestion = Math.max(...q.options.map(o => Number(o.score)));
            maxPossibleScore += maxScoreForThisQuestion;
        });

        // 2. Hitung poin yang didapat user
        Object.values(answers).forEach(ans => totalScore += ans.score);

        // 3. Jadikan persentase (0 - 100%)
        const percentage = maxPossibleScore > 0 ? Math.round((totalScore / maxPossibleScore) * 100) : 0;

        let status, color, Icon, message;
        if (percentage >= 80) {
            status = "Sangat Baik"; color = "text-[#145C33] bg-emerald-50 border-[#145C33]"; Icon = ShieldCheck;
            message = "Luar biasa! Anda sangat patuh terhadap diet rendah garam.";
        } else if (percentage >= 50) {
            status = "Cukup Baik"; color = "text-[#EA580C] bg-orange-50 border-[#EA580C]"; Icon = CheckCircle2;
            message = "Pola makan Anda sudah cukup baik, namun perlu konsistensi lebih.";
        } else {
            status = "Perlu Perbaikan"; color = "text-red-600 bg-red-50 border-red-500"; Icon = AlertTriangle;
            message = "Asupan natrium Anda tergolong tinggi. Yuk, mulai kurangi garam pelan-pelan.";
        }

        return (
            <div className="bg-white rounded-[2rem] p-8 sm:p-10 shadow-sm border border-[#E5EFE9] text-center animate-[slide-up_0.5s_ease-out]">
                <div className={`w-20 h-20 mx-auto rounded-full flex items-center justify-center mb-6 border-4 ${color.replace('text-', 'border-').split(' ')[0]} ${color.split(' ')[1]}`}>
                    <Icon size={40} className={color.split(' ')[0]} />
                </div>
                <h2 className="text-2xl font-black text-slate-900 mb-2">Hasil Evaluasi</h2>
                <p className="text-slate-500 mb-6">Skor Kepatuhan: <strong className="text-[#145C33]">{percentage}%</strong></p>
                <div className={`p-5 rounded-2xl border mb-8 ${color}`}>
                    <h3 className="font-bold mb-1">Status: {status}</h3>
                    <p className="text-sm opacity-90">{message}</p>
                </div>
                <div className="flex gap-4 justify-center">
                    <button onClick={() => window.location.reload()} className="px-6 py-2.5 font-bold text-slate-500 bg-slate-100 rounded-xl hover:bg-slate-200 transition text-sm">Ulangi</button>

                    {/* TOMBOL SIMPAN YANG SUDAH TERHUBUNG KE DATABASE */}
                    <button
                        onClick={() => {
                            // Siapkan format data rincian jawaban untuk dikirim
                            const detailedAnswers = questions.map(q => {
                                const selectedOpt = answers[q.id];
                                const maxP = Math.max(...q.options.map(o => Number(o.score)));
                                return {
                                    question: q.question,
                                    answer: selectedOpt ? selectedOpt.text : "Tidak dijawab",
                                    points: selectedOpt ? selectedOpt.score : 0,
                                    maxPoints: maxP
                                };
                            });

                            // Kirim ke backend Laravel
                            router.post(route('kuis.store'), {
                                score: percentage,
                                status: status,
                                answers: detailedAnswers
                            });
                        }}
                        className="px-6 py-2.5 font-bold text-white bg-[#145C33] rounded-xl hover:bg-emerald-900 transition text-sm shadow-md shadow-emerald-900/20"
                    >
                        Simpan Hasil
                    </button>
                </div>
            </div>
        );
    };

    return (
        <div className="min-h-screen bg-[#F8FBF8] font-sans text-slate-800 pb-24 md:pb-0 relative">
            <Head title="Kuis Kepatuhan Diet" />

            {/* --- NAVBAR ATAS --- */}
            <nav className="fixed top-0 w-full bg-[#F8FBF8]/90 backdrop-blur-md z-40 py-4 border-b border-[#E5EFE9]">
                <div className="max-w-7xl mx-auto px-6 lg:px-8">
                    <div className="flex justify-between items-center">
                        <div className="flex-shrink-0 flex items-center gap-2">
                            <div className="w-8 h-8 rounded-xl bg-gradient-to-br from-[#EA580C] to-[#145C33] flex items-center justify-center text-white font-bold">H</div>
                            <span className="font-bold text-xl text-emerald-900 tracking-tight hidden sm:block">HiperDiet</span>
                        </div>
                        <div className="hidden md:flex space-x-8 items-center">
                            <Link href={route('dashboard')} className="text-slate-500 hover:text-[#EA580C] font-semibold transition text-sm">Beranda</Link>
                            <Link href={route('input.asupan')} className="text-slate-500 hover:text-[#EA580C] font-semibold transition text-sm">Riwayat Makan</Link>
                            <Link href="#" className="text-[#EA580C] font-bold border-b-2 border-[#EA580C] pb-1 text-sm">Kuis Kepatuhan</Link>
                        </div>
                        <div className="relative">
                            <button onClick={() => setShowProfileMenu(!showProfileMenu)} className="flex items-center gap-3 bg-white border border-[#E5EFE9] pl-3 pr-4 py-2 rounded-full hover:shadow-md transition">
                                <div className="w-8 h-8 bg-[#145C33] text-white rounded-full flex items-center justify-center font-bold text-sm">
                                    {auth?.user?.name ? auth.user.name.charAt(0) : 'U'}
                                </div>
                                <span className="text-sm font-bold text-slate-700 hidden sm:block">{auth?.user?.name || 'Pengguna'}</span>
                            </button>
                            {showProfileMenu && (
                                <div className="absolute right-0 mt-2 w-48 bg-white rounded-2xl shadow-xl border border-slate-100 py-2 z-50">
                                    <Link href={route('profile.edit')} className="flex items-center gap-2 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50 hover:text-[#145C33]"><User size={16} /> Profil Saya</Link>
                                    <Link href={route('logout')} method="post" as="button" className="flex w-full items-center gap-2 px-4 py-2 text-sm text-red-600 hover:bg-red-50"><LogOut size={16} /> Keluar</Link>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </nav>

            {/* --- BOTTOM NAVIGATION BAR (Khusus Mobile) --- */}
            <div className="md:hidden fixed bottom-0 w-full bg-white rounded-t-3xl shadow-[0_-10px_40px_rgba(0,0,0,0.08)] z-40 px-6 py-3 pb-safe border-t border-slate-100">
                <div className="flex justify-between items-center text-[10px] font-bold text-slate-400 relative">
                    <Link href={route('dashboard')} className={`flex flex-col items-center gap-1 w-12 ${route().current('dashboard') ? 'text-[#145C33]' : ''}`}>
                        <Home size={24} className={route().current('dashboard') ? 'text-[#145C33]' : ''} />
                        <span>Home</span>
                    </Link>
                    <Link href={route('input.asupan')} className={`flex flex-col items-center gap-1 w-12 mr-6 ${route().current('input.asupan') ? 'text-[#145C33]' : ''}`}>
                        <Activity size={24} className={route().current('input.asupan') ? 'text-[#145C33]' : ''} />
                        <span>Riwayat</span>
                    </Link>
                    <div className="absolute left-1/2 -translate-x-1/2 -top-6">
                        <Link href={route('input.asupan')} className="bg-gradient-to-br from-[#EA580C] to-[#c24100] text-white w-14 h-14 rounded-full flex items-center justify-center shadow-lg shadow-orange-500/30 transform hover:-translate-y-1 transition border-4 border-[#F8FBF8]">
                            <Plus size={28} />
                        </Link>
                    </div>
                    <Link href={route('kuis')} className={`flex flex-col items-center gap-1 w-12 ml-6 ${route().current('kuis') ? 'text-[#145C33]' : ''}`}>
                        <ClipboardCheck size={24} className={route().current('kuis') ? 'text-[#145C33]' : ''} />
                        <span>Kuis</span>
                    </Link>
                    <Link href={route('profile.edit')} className={`flex flex-col items-center gap-1 w-12 ${route().current('profile.edit') ? 'text-[#145C33]' : ''}`}>
                        <User size={24} className={route().current('profile.edit') ? 'text-[#145C33]' : ''} />
                        <span>Profil</span>
                    </Link>
                </div>
            </div>

            {/* --- MAIN CONTENT --- */}
            <main className="pt-28 md:pt-40 max-w-3xl mx-auto px-6 lg:px-8 space-y-8">
                <div className="text-center mb-4">
                    <h1 className="text-3xl font-extrabold text-slate-900 tracking-tight">Kuis <span className="text-[#145C33] italic font-serif">Kepatuhan Diet</span></h1>
                    <p className="text-slate-500 mt-2 text-sm">Evaluasi tingkat kepatuhan diet rendah garam Anda hari ini.</p>
                </div>

                {totalQuestions === 0 ? (
                    // Tampilan jika Admin belum membuat soal kuis
                    <div className="bg-white rounded-[2.5rem] shadow-sm border border-[#E5EFE9] p-12 text-center flex flex-col items-center justify-center">
                        <HelpCircle size={48} className="text-slate-300 mb-4" />
                        <h3 className="text-lg font-bold text-slate-700">Kuis Belum Tersedia</h3>
                        <p className="text-slate-500 text-sm mt-1">Saat ini belum ada pertanyaan kuis dari admin. Silakan kembali lagi nanti.</p>
                        <Link href={route('dashboard')} className="mt-6 text-[#EA580C] font-bold text-sm hover:underline">Kembali ke Beranda</Link>
                    </div>
                ) : (
                    // Tampilan Kuis Utama
                    !isFinished ? (
                        <div className="bg-white rounded-[2.5rem] shadow-sm border border-[#E5EFE9] overflow-hidden">
                            <div className="bg-slate-50 px-8 py-5 border-b border-[#E5EFE9]">
                                <div className="flex justify-between items-center mb-2 text-[10px] font-black uppercase tracking-widest text-slate-400">
                                    <span>Pertanyaan {currentIndex + 1} / {totalQuestions}</span>
                                    <span className="text-[#145C33]">{Math.round(progress)}%</span>
                                </div>
                                <div className="w-full bg-slate-200 rounded-full h-1.5">
                                    <div className="bg-[#145C33] h-1.5 rounded-full transition-all duration-500 ease-out" style={{ width: `${progress}%` }}></div>
                                </div>
                            </div>
                            <div className="p-8 sm:p-10">
                                <h2 className="text-xl sm:text-2xl font-bold text-slate-800 leading-tight mb-8">{currentQuestion.question}</h2>
                                <div className="space-y-4">
                                    {currentQuestion.options.map((option, idx) => {
                                        const isSelected = answers[currentQuestion.id]?.text === option.text;
                                        return (
                                            <button key={idx} onClick={() => handleSelectOption(option.score, option.text)} className={`w-full text-left p-5 rounded-2xl border-2 transition-all ${isSelected ? 'border-[#145C33] bg-emerald-50/50 text-[#145C33] font-bold shadow-sm' : 'border-[#E5EFE9] bg-white text-slate-600 hover:border-slate-300 font-semibold'}`}>
                                                <div className="flex items-center justify-between">
                                                    <span>{option.text}</span>
                                                    <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${isSelected ? 'border-[#145C33]' : 'border-slate-300'}`}>
                                                        {isSelected && <div className="w-2.5 h-2.5 bg-[#145C33] rounded-full"></div>}
                                                    </div>
                                                </div>
                                            </button>
                                        );
                                    })}
                                </div>
                            </div>
                            <div className="bg-slate-50 px-8 py-5 border-t border-[#E5EFE9] flex justify-between">
                                <button onClick={handlePrev} disabled={currentIndex === 0} className="flex items-center gap-2 text-slate-400 font-bold disabled:opacity-30 hover:text-slate-800 transition text-sm"><ChevronLeft size={18} /> Kembali</button>
                                <button onClick={handleNext} disabled={!answers[currentQuestion.id]} className="bg-[#EA580C] text-white px-6 py-2.5 rounded-xl font-bold hover:bg-[#c24100] transition disabled:opacity-50 shadow-md shadow-orange-500/20 text-sm flex items-center gap-2">
                                    {currentIndex === totalQuestions - 1 ? 'Selesai' : 'Selanjutnya'} <ChevronRight size={18} />
                                </button>
                            </div>
                        </div>
                    ) : renderResult()
                )}
            </main>
        </div>
    );
}
