import { Head, Link } from '@inertiajs/react';
import { useMemo } from 'react';
import { ArrowLeft, Printer, AlertTriangle, CheckCircle2, Award, Calendar, BookOpen } from 'lucide-react';
import { evaluateKktp, getCategoryInfo } from '@/lib/kktp';
import { formatDate } from '@/lib/utils';
import type { PageProps } from '@/types';

interface Student {
    id: number;
    nisn: string;
    full_name: string;
}

interface Submission {
    id: number;
    assignment_id: number;
    student_id: number;
    status: string;
    grade: number | null;
    original_grade?: number | null;
    remedial_count?: number;
    is_remedial?: boolean;
    remedial_history?: Array<{ attempt: number; initial_score: number; remedial_score: number; date: string; notes?: string | null }> | null;
    feedback: string | null;
}

interface TargetClass {
    id: number;
    name: string;
}

interface Assignment {
    id: number;
    title: string;
    description: string | null;
    due_date: string;
    max_points: number;
    kktp?: number;
    category?: string;
    submission_type: string;
    academic_year?: { name: string } | null;
    semester?: { semester: number } | null;
    material: {
        id: number;
        title: string;
        subject: { id: number; name: string };
        teacher?: { id: number; name: string; nip?: string | null } | null;
    };
}

interface Props extends PageProps {
    assignment: Assignment;
    targetClasses: TargetClass[];
    selectedClass?: TargetClass | null;
    students: Student[];
    submissions: Record<number, Submission>;
}

export default function PrintRecap({ assignment, targetClasses, selectedClass, students, submissions }: Props) {
    const kktpThreshold = assignment.kktp ?? 75;
    const categoryInfo = getCategoryInfo(assignment.category);

    const stats = useMemo(() => {
        let graded = 0;
        let tuntas = 0;
        let needsRemedial = 0;
        let remedialDone = 0;
        let totalScore = 0;
        let maxScore = -Infinity;
        let minScore = Infinity;

        let sangatBaik = 0;
        let baik = 0;
        let cukup = 0;
        let perluBimbingan = 0;

        const remedialList: Array<{
            student: Student;
            initialGrade: number | null;
            finalGrade: number | null;
            isCompleted: boolean;
            remedialCount: number;
            evaluation: ReturnType<typeof evaluateKktp>;
        }> = [];

        students.forEach((student) => {
            const sub = submissions[student.id];
            const hasGrade = sub?.status === 'graded' && sub.grade !== null && sub.grade !== undefined;

            if (hasGrade) {
                const score = Number(sub.grade);
                graded++;
                totalScore += score;
                if (score > maxScore) maxScore = score;
                if (score < minScore) minScore = score;

                const evaluation = evaluateKktp(score, kktpThreshold);

                if (score >= 90) sangatBaik++;
                else if (score >= kktpThreshold) baik++;
                else if (score >= 60) cukup++;
                else perluBimbingan++;

                const isRemedialCompleted = Boolean(sub.is_remedial || (sub.original_grade !== null && sub.original_grade !== undefined));
                const isUnderKktp = score < kktpThreshold;

                if (score >= kktpThreshold) {
                    tuntas++;
                } else {
                    needsRemedial++;
                }

                if (isRemedialCompleted) {
                    remedialDone++;
                }

                if (isRemedialCompleted || isUnderKktp) {
                    remedialList.push({
                        student,
                        initialGrade: sub.original_grade !== null && sub.original_grade !== undefined ? Number(sub.original_grade) : (isUnderKktp ? score : null),
                        finalGrade: isRemedialCompleted ? score : null,
                        isCompleted: isRemedialCompleted,
                        remedialCount: sub.remedial_count ?? (isRemedialCompleted ? 1 : 0),
                        evaluation,
                    });
                }
            }
        });

        const avgScore = graded > 0 ? (totalScore / graded).toFixed(1) : '-';
        const tuntasPct = graded > 0 ? Math.round((tuntas / graded) * 100) : 0;

        return {
            total: students.length,
            graded,
            ungraded: students.length - graded,
            tuntas,
            remedial: needsRemedial,
            needsRemedial,
            remedialDone,
            tuntasPct,
            avgScore,
            maxScore: maxScore === -Infinity ? '-' : maxScore,
            minScore: minScore === Infinity ? '-' : minScore,
            sangatBaik,
            baik,
            cukup,
            perluBimbingan,
            remedialList,
        };
    }, [students, submissions, kktpThreshold]);

    const handlePrint = () => {
        window.print();
    };

    const todayDateFormatted = new Intl.DateTimeFormat('id-ID', {
        day: 'numeric',
        month: 'long',
        year: 'numeric',
    }).format(new Date());

    return (
        <div className="min-h-screen bg-neutral-900 text-slate-100 font-sans print:bg-white print:text-black">
            <Head title={`Rekap & Remedial: ${assignment.title} - ${selectedClass?.name || ''}`} />

            {/* Print-specific style overrides */}
            <style>{`
                @media print {
                    @page {
                        size: A4 portrait;
                        margin: 14mm 12mm 14mm 12mm;
                    }
                    body {
                        background: #ffffff !important;
                        color: #0f172a !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }
                    .no-print {
                        display: none !important;
                    }
                    .print-table {
                        border-collapse: collapse !important;
                        width: 100% !important;
                    }
                    .print-table th, .print-table td {
                        border: 1px solid #cbd5e1 !important;
                        padding: 5px 8px !important;
                        font-size: 11px !important;
                    }
                    .print-table th {
                        background-color: #f1f5f9 !important;
                        color: #0f172a !important;
                    }
                    .page-break {
                        page-break-before: always;
                    }
                }
            `}</style>

            {/* Top Interactive Toolbar (Hidden on Print) */}
            <header className="no-print sticky top-0 z-30 border-b border-white/10 bg-neutral-900/90 backdrop-blur-md px-4 py-3 sm:px-8">
                <div className="mx-auto flex max-w-5xl flex-wrap items-center justify-between gap-3">
                    <div className="flex items-center gap-3">
                        <Link
                            href={`/assignments/${assignment.id}/review${selectedClass ? `?class_id=${selectedClass.id}` : ''}`}
                            className="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3.5 py-2 text-xs font-semibold text-slate-300 hover:bg-white/10 hover:text-white transition-colors"
                        >
                            <ArrowLeft className="h-4 w-4" />
                            Kembali ke Review
                        </Link>
                        {targetClasses.length > 1 && (
                            <div className="flex items-center gap-2">
                                <span className="text-xs text-slate-400">Pilih Kelas:</span>
                                <div className="flex gap-1.5">
                                    {targetClasses.map((c) => (
                                        <Link
                                            key={c.id}
                                            href={`/assignments/${assignment.id}/print-recap?class_id=${c.id}`}
                                            className={`rounded-lg px-2.5 py-1 text-xs font-bold transition-all ${
                                                selectedClass?.id === c.id
                                                    ? 'bg-amber-500 text-slate-950 shadow-xs'
                                                    : 'bg-white/5 text-slate-400 hover:bg-white/10'
                                            }`}
                                        >
                                            {c.name}
                                        </Link>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>

                    <div className="flex items-center gap-3">
                        <button
                            type="button"
                            onClick={handlePrint}
                            className="inline-flex items-center gap-2 rounded-xl bg-amber-500 px-5 py-2 text-xs font-bold text-slate-950 shadow-md shadow-amber-500/20 hover:bg-amber-400 active:scale-98 transition-all cursor-pointer"
                        >
                            <Printer className="h-4 w-4" />
                            Cetak / Simpan PDF
                        </button>
                    </div>
                </div>
            </header>

            {/* Document Paper Container */}
            <main className="mx-auto my-6 max-w-5xl bg-white p-6 text-slate-900 shadow-2xl rounded-2xl sm:p-10 print:my-0 print:p-0 print:shadow-none print:rounded-none">
                {/* Official Letterhead / Header */}
                <div className="border-b-2 border-slate-900 pb-4 text-center">
                    <h1 className="text-lg font-black uppercase tracking-wider text-slate-900 sm:text-xl">
                        Laporan Rekapitulasi Asesmen & Analisis Ketercapaian TP (KKTP)
                    </h1>
                    <p className="text-xs font-medium uppercase tracking-widest text-slate-600 mt-1">
                        Kurikulum Merdeka &bull; Panduan Pembelajaran dan Asesmen
                    </p>
                </div>

                {/* Metadata Grid */}
                <div className="mt-4 grid grid-cols-2 gap-x-6 gap-y-2 border border-slate-300 rounded-lg p-3 text-xs bg-slate-50/70 sm:grid-cols-4 print:bg-transparent print:p-2.5">
                    <div>
                        <span className="text-slate-500 block text-[11px]">Mata Pelajaran:</span>
                        <strong className="text-slate-900 font-bold">{assignment.material.subject.name}</strong>
                    </div>
                    <div>
                        <span className="text-slate-500 block text-[11px]">Kelas:</span>
                        <strong className="text-slate-900 font-bold">{selectedClass?.name || '-'}</strong>
                    </div>
                    <div>
                        <span className="text-slate-500 block text-[11px]">Kategori Asesmen:</span>
                        <strong className="text-slate-900 font-bold">{categoryInfo.label}</strong>
                    </div>
                    <div>
                        <span className="text-slate-500 block text-[11px]">Batas Tuntas KKTP:</span>
                        <strong className="text-slate-900 font-bold">&ge; {kktpThreshold} Poin</strong>
                    </div>
                    <div className="col-span-2">
                        <span className="text-slate-500 block text-[11px]">Judul Tugas / Instrumen:</span>
                        <strong className="text-slate-900 font-bold">{assignment.title}</strong>
                    </div>
                    <div>
                        <span className="text-slate-500 block text-[11px]">Materi Pokok:</span>
                        <strong className="text-slate-900 font-bold">{assignment.material.title}</strong>
                    </div>
                    <div>
                        <span className="text-slate-500 block text-[11px]">Guru Pengampu:</span>
                        <strong className="text-slate-900 font-bold">{assignment.material.teacher?.name || '-'}</strong>
                    </div>
                </div>

                {/* Quick Diagnostics Stats Box */}
                <div className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-6 text-center text-xs">
                    <div className="border border-slate-300 rounded-lg p-2.5 bg-slate-50 print:bg-transparent">
                        <span className="text-slate-500 text-[10px] uppercase font-semibold block">Total Siswa</span>
                        <span className="text-base font-black text-slate-900">{stats.total}</span>
                    </div>
                    <div className="border border-slate-300 rounded-lg p-2.5 bg-slate-50 print:bg-transparent">
                        <span className="text-slate-500 text-[10px] uppercase font-semibold block">Telah Dinilai</span>
                        <span className="text-base font-black text-slate-900">{stats.graded}</span>
                    </div>
                    <div className="border border-emerald-300 bg-emerald-50/60 rounded-lg p-2.5 print:border-slate-300 print:bg-transparent">
                        <span className="text-emerald-800 text-[10px] uppercase font-bold block print:text-slate-700">Tuntas KKTP</span>
                        <span className="text-base font-black text-emerald-700 print:text-slate-900">
                            {stats.tuntas} <span className="text-xs font-normal">({stats.tuntasPct}%)</span>
                        </span>
                    </div>
                    <div className="border border-rose-300 bg-rose-50/60 rounded-lg p-2.5 print:border-slate-300 print:bg-transparent">
                        <span className="text-rose-800 text-[10px] uppercase font-bold block print:text-slate-700">Butuh Remedial</span>
                        <span className="text-base font-black text-rose-700 print:text-slate-900">{stats.remedial}</span>
                    </div>
                    <div className="border border-slate-300 rounded-lg p-2.5 bg-slate-50 print:bg-transparent">
                        <span className="text-slate-500 text-[10px] uppercase font-semibold block">Rata-rata</span>
                        <span className="text-base font-black text-slate-900">{stats.avgScore}</span>
                    </div>
                    <div className="border border-slate-300 rounded-lg p-2.5 bg-slate-50 print:bg-transparent">
                        <span className="text-slate-500 text-[10px] uppercase font-semibold block">Rentang (Min - Max)</span>
                        <span className="text-base font-black text-slate-900">
                            {stats.minScore} - {stats.maxScore}
                        </span>
                    </div>
                </div>

                {/* Interval Distribution Table */}
                <div className="mt-4 border border-slate-300 rounded-lg overflow-hidden text-xs">
                    <div className="bg-slate-100 px-3 py-1.5 font-bold text-slate-800 border-b border-slate-300 text-[11px] uppercase tracking-wide">
                        Distribusi Interval KKTP Kurikulum Merdeka (PPA 2025)
                    </div>
                    <div className="grid grid-cols-2 divide-x divide-y sm:grid-cols-4 sm:divide-y-0 text-center">
                        <div className="p-2">
                            <span className="block text-[11px] font-bold text-emerald-700 print:text-slate-800">Sangat Baik (90 - 100)</span>
                            <span className="text-sm font-black text-slate-900">{stats.sangatBaik} Siswa</span>
                            <span className="block text-[10px] text-slate-500 mt-0.5">Pengayaan Mandiri</span>
                        </div>
                        <div className="p-2">
                            <span className="block text-[11px] font-bold text-cyan-700 print:text-slate-800">Baik ({kktpThreshold} - 89)</span>
                            <span className="text-sm font-black text-slate-900">{stats.baik} Siswa</span>
                            <span className="block text-[10px] text-slate-500 mt-0.5">Tuntas / Lanjut Materi</span>
                        </div>
                        <div className="p-2">
                            <span className="block text-[11px] font-bold text-amber-700 print:text-slate-800">Cukup (60 - {kktpThreshold - 1})</span>
                            <span className="text-sm font-black text-slate-900">{stats.cukup} Siswa</span>
                            <span className="block text-[10px] text-slate-500 mt-0.5">Remedial Terarah</span>
                        </div>
                        <div className="p-2">
                            <span className="block text-[11px] font-bold text-rose-700 print:text-slate-800">Perlu Bimbingan (0 - 59)</span>
                            <span className="text-sm font-black text-slate-900">{stats.perluBimbingan} Siswa</span>
                            <span className="block text-[10px] text-slate-500 mt-0.5">Remedial Menyeluruh</span>
                        </div>
                    </div>
                </div>

                {/* Main Table: Rekap Capaian Siswa */}
                <div className="mt-5">
                    <h2 className="text-sm font-bold uppercase tracking-wider text-slate-800 mb-2">
                        I. Daftar Nilai & Status Ketercapaian Seluruh Siswa
                    </h2>
                    <table className="print-table w-full border-collapse text-left text-xs border border-slate-300">
                        <thead>
                            <tr className="bg-slate-100 text-slate-800 font-bold border-b border-slate-300">
                                <th className="py-2 px-2 text-center w-8">No</th>
                                <th className="py-2 px-3 w-28">NISN</th>
                                <th className="py-2 px-3">Nama Peserta Didik</th>
                                <th className="py-2 px-3 text-center w-16">Nilai</th>
                                <th className="py-2 px-3 text-center w-28">Predikat</th>
                                <th className="py-2 px-3 text-center w-24">Ketuntasan</th>
                                <th className="py-2 px-3">Tindak Lanjut Kurikulum Merdeka</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-200">
                            {students.map((student, idx) => {
                                const sub = submissions[student.id];
                                const hasGrade = sub?.status === 'graded' && sub.grade !== null && sub.grade !== undefined;
                                const score = hasGrade ? Number(sub.grade) : null;
                                const evalResult = evaluateKktp(score, kktpThreshold);

                                return (
                                    <tr key={student.id} className={idx % 2 === 1 ? 'bg-slate-50/50 print:bg-transparent' : ''}>
                                        <td className="py-1.5 px-2 text-center text-slate-500">{idx + 1}</td>
                                        <td className="py-1.5 px-3 font-mono text-[11px] text-slate-600">{student.nisn || '-'}</td>
                                        <td className="py-1.5 px-3 font-semibold text-slate-900">{student.full_name}</td>
                                        <td className="py-1.5 px-3 text-center font-bold font-mono text-slate-900">
                                            {hasGrade ? (
                                                <span>
                                                    {score}
                                                    {Boolean(sub?.is_remedial || (sub?.original_grade !== null && sub?.original_grade !== undefined)) && (
                                                        <span
                                                            className="ml-0.5 text-[10px] font-bold text-amber-700 print:text-slate-700"
                                                            title={`Hasil Remedial (Nilai Awal: ${sub.original_grade ?? '-'})`}
                                                        >
                                                            *
                                                        </span>
                                                    )}
                                                </span>
                                            ) : (
                                                <span className="text-slate-400 font-normal italic">-</span>
                                            )}
                                        </td>
                                        <td className="py-1.5 px-3 text-center text-[11px]">
                                            {evalResult ? (
                                                <span className="font-semibold">{evalResult.predikat}</span>
                                            ) : (
                                                <span className="text-slate-400 italic">Belum Dinilai</span>
                                            )}
                                        </td>
                                        <td className="py-1.5 px-3 text-center text-[11px]">
                                            {evalResult ? (
                                                evalResult.isTuntas ? (
                                                    Boolean(sub?.is_remedial || (sub?.original_grade !== null && sub?.original_grade !== undefined)) ? (
                                                        <span className="font-bold text-amber-700 print:text-slate-900">
                                                            TUNTAS (R)*
                                                        </span>
                                                    ) : (
                                                        <span className="font-bold text-emerald-700 print:text-slate-900">TUNTAS</span>
                                                    )
                                                ) : (
                                                    <span className="font-black text-rose-700 print:font-bold print:text-slate-900 underline decoration-rose-400">
                                                        REMEDIAL
                                                    </span>
                                                )
                                            ) : (
                                                <span className="text-slate-400">-</span>
                                            )}
                                        </td>
                                        <td className="py-1.5 px-3 text-[11px] text-slate-600">
                                            {evalResult?.tindakLanjut || (hasGrade ? '-' : 'Menunggu pengumpulan / penilaian')}
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                    <p className="mt-1.5 text-[10px] text-slate-500 italic">
                        *) Nilai akhir diperoleh melalui kegiatan tindak lanjut perbaikan/remedial (data nilai awal tercatat pada Bagian II Berita Acara Remedial).
                    </p>
                </div>

                {/* Section II: Daftar Siswa Tindak Lanjut Remedial */}
                {stats.remedialList.length > 0 && (
                    <div className="mt-6 page-break">
                        <div className="flex items-center justify-between mb-2">
                            <h2 className="text-sm font-bold uppercase tracking-wider text-slate-800">
                                II. Berita Acara & Rekapitulasi Pelaksanaan Remedial (KKTP: {kktpThreshold})
                            </h2>
                            <span className="text-xs font-semibold text-slate-500">
                                Total: {stats.remedialList.length} Siswa Teridentifikasi ({stats.remedialDone} Tuntas, {stats.needsRemedial} Belum)
                            </span>
                        </div>
                        <table className="print-table w-full border-collapse text-left text-xs border border-slate-300">
                            <thead>
                                <tr className="bg-slate-100 text-slate-800 font-bold border-b border-slate-300">
                                    <th className="py-2 px-2 text-center w-8">No</th>
                                    <th className="py-2 px-3 w-28">NISN</th>
                                    <th className="py-2 px-3">Nama Siswa</th>
                                    <th className="py-2 px-3 text-center w-20">Nilai Awal</th>
                                    <th className="py-2 px-3 text-center w-24">Bentuk Remedial</th>
                                    <th className="py-2 px-3 text-center w-24">Nilai Akhir</th>
                                    <th className="py-2 px-3 text-center w-28">Paraf Siswa</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-200">
                                {stats.remedialList.map((item, idx) => (
                                    <tr key={item.student.id} className="h-9">
                                        <td className="py-2 px-2 text-center text-slate-500">{idx + 1}</td>
                                        <td className="py-2 px-3 font-mono text-[11px] text-slate-600">{item.student.nisn || '-'}</td>
                                        <td className="py-2 px-3 font-semibold text-slate-900">{item.student.full_name}</td>
                                        <td className="py-2 px-3 text-center font-bold font-mono text-rose-700 print:text-slate-900">
                                            {item.initialGrade !== null ? item.initialGrade : '-'}
                                        </td>
                                        <td className="py-2 px-3 text-center text-slate-600 text-[11px] italic print:text-slate-700">
                                            Tugas / Tes Ulang
                                        </td>
                                        <td className="py-2 px-3 text-center font-bold font-mono">
                                            {item.finalGrade !== null ? (
                                                <span className="text-emerald-700 print:text-slate-900">
                                                    {item.finalGrade}{' '}
                                                    <span className="text-[10px] font-normal text-slate-500">(Tuntas)</span>
                                                </span>
                                            ) : (
                                                <span className="text-rose-600 font-medium italic text-[11px] print:text-slate-600">
                                                    Belum Tuntas
                                                </span>
                                            )}
                                        </td>
                                        <td className="py-2 px-3 text-center text-slate-400"></td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}

                {/* Section III: Tanda Tangan & Pengesahan */}
                <div className="mt-8 pt-6 border-t border-slate-300 flex justify-between text-xs text-slate-800">
                    <div className="text-center w-56">
                        <p className="font-medium text-slate-600">Mengetahui,</p>
                        <p className="font-bold text-slate-900">Kepala Sekolah</p>
                        <div className="h-20" />
                        <p className="font-bold border-b border-slate-900 inline-block px-4">
                            __________________________
                        </p>
                        <p className="text-[11px] text-slate-500 mt-0.5">NIP. -</p>
                    </div>

                    <div className="text-center w-56">
                        <p className="font-medium text-slate-600">
                            {todayDateFormatted}
                        </p>
                        <p className="font-bold text-slate-900">Guru Mata Pelajaran</p>
                        <div className="h-20" />
                        <p className="font-bold border-b border-slate-900 inline-block px-4">
                            {assignment.material.teacher?.name || '__________________________'}
                        </p>
                        <p className="text-[11px] text-slate-500 mt-0.5">
                            NIP. {assignment.material.teacher?.nip || '-'}
                        </p>
                    </div>
                </div>
            </main>
        </div>
    );
}
