"use client";

import React, { useState, useMemo, useEffect, useRef } from "react";
import Link from "next/link";
import {
  FileBarChart,
  Search,
  Filter,
  Download,
  Upload,
  Printer,
  Eye,
  Edit3,
  Award,
  Users,
  CheckCircle,
  AlertCircle,
  RefreshCw,
  FileSpreadsheet,
  ArrowRight,
  TrendingUp,
  GraduationCap,
  Sparkles,
  HelpCircle,
  ChevronRight,
  Sliders,
} from "lucide-react";
import { PageHeader } from "@/components/shared/PageHeader";
import { StatCard } from "@/components/ui/StatCard";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Select } from "@/components/ui/Select";
import { Badge } from "@/components/ui/Badge";
import { Toast } from "@/components/ui/Toast";
import { Modal } from "@/components/ui/Modal";
import { EmptyState } from "@/components/ui/EmptyState";
import { Pagination } from "@/components/ui/Pagination";
import { brandConfig } from "@/config/brand";
import {
  SKLConfig,
  SKLRecord,
  DEFAULT_SKL_CONFIG,
  DEFAULT_PAPER_SETTINGS,
  SKLPaperSettings,
  initialMockSKLRecords,
  formatIndonesianScore,
  calculateSKLAverage,
  generateLetterNumber,
  isDummySKLRecord,
  buildSKLRecordFromStudent,
} from "@/data/mockSKLData";
import { useSmartSchool } from "@/context/SmartSchoolContext";
import dynamic from "next/dynamic";
import {
  downloadFinalGradesTemplateXLSX,
  parseFinalGradesExcelFile,
  FinalGradesImportRow,
} from "@/lib/excelUtils";
import { SKLDocumentSheet } from "@/components/skl/SKLDocumentSheet";

const SKLPreviewModal = dynamic(
  () => import("@/components/skl/SKLPreviewModal").then((mod) => mod.SKLPreviewModal),
  { ssr: false }
);
const SKLEditModal = dynamic(
  () => import("@/components/skl/SKLEditModal").then((mod) => mod.SKLEditModal),
  { ssr: false }
);
const SKLPaperSettingsModal = dynamic(
  () => import("@/components/skl/SKLPaperSettingsModal").then((mod) => mod.SKLPaperSettingsModal),
  { ssr: false }
);
const SKLPeminatanModal = dynamic(
  () => import("@/components/skl/SKLPeminatanModal").then((mod) => mod.SKLPeminatanModal),
  { ssr: false }
);

const CLASS_OPTIONS = [
  { label: "Semua Kelas XII", value: "Semua" },
  { label: "Kelas XII-1", value: "XII-1" },
  { label: "Kelas XII-2", value: "XII-2" },
  { label: "Kelas XII-3", value: "XII-3" },
  { label: "Kelas XII-4", value: "XII-4" },
  { label: "Kelas XII-5", value: "XII-5" },
  { label: "Kelas XII-6", value: "XII-6" },
  { label: "Kelas XII-7", value: "XII-7" },
  { label: "Kelas XII-8", value: "XII-8" },
  { label: "Kelas XII-9", value: "XII-9" },
  { label: "Kelas XII-10", value: "XII-10" },
];

const SUBJECT_COLUMNS = [
  { key: "SKL-01", short: "PAI", label: "Pendidikan Agama & Budi Pekerti" },
  { key: "SKL-02", short: "Pancasila", label: "Pendidikan Pancasila" },
  { key: "SKL-03", short: "B. Indo", label: "Bahasa Indonesia" },
  { key: "SKL-04", short: "MTK", label: "Matematika" },
  { key: "SKL-05", short: "Info", label: "Informatika" },
  { key: "SKL-06", short: "Fisika", label: "Fisika" },
  { key: "SKL-07", short: "Kimia", label: "Kimia" },
  { key: "SKL-08", short: "Biologi", label: "Biologi" },
  { key: "SKL-09", short: "Ekonomi", label: "Ekonomi" },
  { key: "SKL-10", short: "B. Ing", label: "Bahasa Inggris" },
  { key: "SKL-11", short: "Sejarah", label: "Sejarah" },
  { key: "SKL-12", short: "PJOK", label: "PJOK" },
  { key: "SKL-13", short: "Seni", label: "Seni" },
  { key: "SKL-14", short: "B. Sunda", label: "Bahasa Sunda" },
  { key: "SKL-15", short: "Pilihan 1", label: "Mapel Pilihan 1" },
  { key: "SKL-16", short: "Pilihan 2", label: "Mapel Pilihan 2" },
];

export default function NilaiAkhirKelasXIIPage() {
  // Config state (shared with SKL)
  const [sklConfig, setSklConfig] = useState<SKLConfig>(() => {
    if (typeof window !== "undefined") {
      try {
        const saved = localStorage.getItem("bpi_smartschool_skl_config");
        if (saved) {
          const parsed = JSON.parse(saved);
          return {
            ...DEFAULT_SKL_CONFIG,
            ...parsed,
            showStampAndSignature: false,
          };
        }
      } catch (e) {
        console.error("Failed to parse skl config:", e);
      }
    }
    return DEFAULT_SKL_CONFIG;
  });

  // SmartSchool Context
  const { students: contextStudents, isLoadingStudents } = useSmartSchool();

  // Records state (shared with SKL)
  const [sklRecords, setSklRecords] = useState<SKLRecord[]>(() => {
    if (typeof window !== "undefined") {
      try {
        const saved = localStorage.getItem("bpi_smartschool_skl_records");
        if (saved) {
          const parsed = JSON.parse(saved);
          if (Array.isArray(parsed)) {
            return parsed.filter((r: any) => !isDummySKLRecord(r));
          }
        }
      } catch (e) {
        console.error("Failed to parse skl records:", e);
      }
    }
    return [];
  });

  // Dynamically load real Kelas XII students from Data Siswa and purge dummy mock records
  useEffect(() => {
    let isMounted = true;
    async function syncKelasXIIStudents() {
      // 1. Get Kelas XII students from context or API
      let gradeXII = (contextStudents || []).filter(
        (s) =>
          s.gradeLevel === "XII" ||
          (s.className && s.className.startsWith("XII-"))
      );

      if (gradeXII.length === 0) {
        try {
          const res = await fetch("/api/students?grade=XII");
          if (res.ok) {
            const json = await res.json();
            if (json.success && Array.isArray(json.data)) {
              gradeXII = json.data.map((item: any) => ({
                id: String(item.id || item.nis),
                nis: item.nis,
                nisn: item.nisn,
                fullName: item.nama_lengkap || item.fullName,
                gender: item.jenis_kelamin?.startsWith("L") ? "L" : "P",
                gradeLevel: "XII",
                className: item.rombel || item.className || "XII-1",
                status: item.status || "aktif",
                birthPlace: item.tempat_lahir || "Bandung",
                birthDate: item.tanggal_lahir || "-",
                parentName: item.nama_ortu_wali || item.parentName || "-",
                parentPhone: item.no_wa_ortu || item.parentPhone || "-",
                address: item.alamat || item.address || "-",
              }));
            }
          }
        } catch (err) {
          console.warn("Could not fetch Kelas XII students from API:", err);
        }
      }

      if (!isMounted || gradeXII.length === 0) return;

      // 2. Read existing saved records and purge dummy data
      const savedValidMap = new Map<string, SKLRecord>();
      if (typeof window !== "undefined") {
        try {
          const saved = localStorage.getItem("bpi_smartschool_skl_records");
          if (saved) {
            const parsed = JSON.parse(saved);
            if (Array.isArray(parsed)) {
              parsed.forEach((rec: SKLRecord) => {
                if (!isDummySKLRecord(rec) && rec.nis) {
                  savedValidMap.set(rec.nis.trim(), rec);
                }
              });
            }
          }
        } catch (e) {
          console.error("Error reading saved SKL records:", e);
        }
      }

      // Sort genuine students by rombel (XII-1 to XII-10) and then student name
      const sortedStudents = [...gradeXII].sort((a, b) => {
        const clsComp = (a.className || "").localeCompare(b.className || "", undefined, {
          numeric: true,
        });
        if (clsComp !== 0) return clsComp;
        return (a.fullName || "").localeCompare(b.fullName || "");
      });

      let classPeminatanMap: Record<string, string> = {};
      if (typeof window !== "undefined") {
        try {
          const rawMap = localStorage.getItem("bpi_smartschool_rombel_peminatan");
          if (rawMap) classPeminatanMap = JSON.parse(rawMap);
        } catch (e) {
          console.error("Failed to read rombel peminatan mapping:", e);
        }
      }

      // 3. Merge genuine students with saved grades
      const mergedRecords: SKLRecord[] = sortedStudents.map((std, idx) => {
        const existing = savedValidMap.get(std.nis.trim());
        return buildSKLRecordFromStudent(
          std,
          sklConfig.startingNumber + idx,
          sklConfig,
          existing,
          classPeminatanMap
        );
      });

      setSklRecords(mergedRecords);
      if (typeof window !== "undefined") {
        try {
          localStorage.setItem(
            "bpi_smartschool_skl_records",
            JSON.stringify(mergedRecords)
          );
        } catch (e) {
          console.error("Failed to sync skl records to storage:", e);
        }
      }
    }

    syncKelasXIIStudents();

    return () => {
      isMounted = false;
    };
  }, [
    contextStudents,
    sklConfig.startingNumber,
    sklConfig.letterNumberFormat,
    sklConfig.academicYear,
  ]);


  // Filters
  const [selectedClass, setSelectedClass] = useState<string>("Semua");
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [statusFilter, setStatusFilter] = useState<string>("Semua");

  // Pagination
  const [currentPage, setCurrentPage] = useState<number>(1);
  const itemsPerPage = 10;

  // Modals state
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [isPaperSettingsOpen, setIsPaperSettingsOpen] = useState(false);
  const [isPeminatanModalOpen, setIsPeminatanModalOpen] = useState(false);
  const [importFile, setImportFile] = useState<File | null>(null);
  const [importRows, setImportRows] = useState<FinalGradesImportRow[] | null>(null);
  const [isParsingExcel, setIsParsingExcel] = useState(false);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const [previewRecord, setPreviewRecord] = useState<SKLRecord | null>(null);
  const [editRecord, setEditRecord] = useState<SKLRecord | null>(null);
  const [printingRecord, setPrintingRecord] = useState<SKLRecord | null>(null);

  // Save config
  const handleSaveConfig = (newConfig: SKLConfig) => {
    setSklConfig(newConfig);
    if (typeof window !== "undefined") {
      try {
        localStorage.setItem("bpi_smartschool_skl_config", JSON.stringify(newConfig));
      } catch (e) {
        console.error("Failed to save skl config:", e);
      }
    }
  };

  // Save paper settings
  const handleSavePaperSettings = (newPaper: SKLPaperSettings) => {
    const updated = {
      ...sklConfig,
      paperSettings: newPaper,
    };
    handleSaveConfig(updated);
    showToast(`Ukuran kertas ${newPaper.paperSize} (${newPaper.scale}%) berhasil diterapkan!`, "success");
  };

  // Toast
  const [toast, setToast] = useState<{
    show: boolean;
    message: string;
    type: "success" | "error" | "info";
  }>({
    show: false,
    message: "",
    type: "success",
  });

  const showToast = (
    message: string,
    type: "success" | "error" | "info" = "success"
  ) => {
    setToast({ show: true, message, type });
  };

  // Sync to localStorage whenever sklRecords changes
  const saveRecords = (newRecords: SKLRecord[]) => {
    setSklRecords(newRecords);
    if (typeof window !== "undefined") {
      try {
        localStorage.setItem(
          "bpi_smartschool_skl_records",
          JSON.stringify(newRecords)
        );
      } catch (e) {
        console.error("Failed to save skl records:", e);
      }
    }
  };

  // Filtered records
  const filteredRecords = useMemo(() => {
    return sklRecords.filter((rec) => {
      // Class filter
      if (selectedClass !== "Semua" && rec.className !== selectedClass) {
        return false;
      }
      // Status filter
      if (statusFilter === "BELUM_DINILAI") {
        if ((rec.overallAverage || 0) > 0) return false;
      } else if (statusFilter === "LULUS" || statusFilter === "TIDAK LULUS") {
        if ((rec.overallAverage || 0) === 0 || rec.status !== statusFilter) return false;
      }
      // Search query
      if (searchQuery.trim()) {
        const q = searchQuery.toLowerCase();
        const matchName = rec.fullName.toLowerCase().includes(q);
        const matchNis = rec.nis.toLowerCase().includes(q);
        const matchNisn = rec.nisn.toLowerCase().includes(q);
        return matchName || matchNis || matchNisn;
      }
      return true;
    });
  }, [sklRecords, selectedClass, statusFilter, searchQuery]);

  // Pagination calculation
  const totalPages = Math.ceil(filteredRecords.length / itemsPerPage) || 1;
  const paginatedRecords = useMemo(() => {
    const start = (currentPage - 1) * itemsPerPage;
    return filteredRecords.slice(start, start + itemsPerPage);
  }, [filteredRecords, currentPage, itemsPerPage]);

  // Overall statistics
  const stats = useMemo(() => {
    const dataset = filteredRecords.length > 0 ? filteredRecords : sklRecords;
    if (dataset.length === 0) {
      return {
        total: 0,
        average: 0,
        passCount: 0,
        passRate: 0,
        maxScore: 0,
        minScore: 0,
        totalScored: 0,
      };
    }
    const total = dataset.length;
    const scoredStudents = dataset.filter((r) => (Number(r.overallAverage) || 0) > 0);
    const totalScored = scoredStudents.length;

    let average = 0;
    let maxScore = 0;
    let minScore = 0;

    if (totalScored > 0) {
      const totalAvgSum = scoredStudents.reduce(
        (sum, r) => sum + (Number(r.overallAverage) || 0),
        0
      );
      average = Number((totalAvgSum / totalScored).toFixed(2));
      maxScore = Math.max(...scoredStudents.map((r) => Number(r.overallAverage) || 0));
      minScore = Math.min(...scoredStudents.map((r) => Number(r.overallAverage) || 0));
    }

    const passCount = scoredStudents.filter((r) => r.status === "LULUS").length;
    const passRate = totalScored > 0 ? Math.round((passCount / totalScored) * 100) : 0;

    return { total, average, passCount, passRate, maxScore, minScore, totalScored };
  }, [filteredRecords, sklRecords]);

  // Handle single student instant print
  const handlePrintStudent = (record: SKLRecord) => {
    setPrintingRecord(record);
    if (typeof document !== "undefined") {
      document.body.style.overflow = "visible";
    }
    setTimeout(() => {
      window.print();
    }, 250);
  };

  // Handle saving manual edits
  const handleSaveEdit = (updated: SKLRecord) => {
    const nextList = sklRecords.map((r) => (r.id === updated.id ? updated : r));
    saveRecords(nextList);
    showToast(
      `Nilai akhir & SKL ${updated.fullName} berhasil diperbarui (Rata-rata: ${formatIndonesianScore(
        updated.overallAverage
      )})`
    );
  };

  // Handle 1-click batch class peminatan update
  const handleApplyPeminatan = (updatedRecords: SKLRecord[], message: string) => {
    saveRecords(updatedRecords);
    if (typeof window !== "undefined") {
      try {
        const classMap: Record<string, string> = {};
        updatedRecords.forEach((r) => {
          if (r.className && r.peminatanPaket) {
            classMap[r.className] = r.peminatanPaket;
          }
        });
        localStorage.setItem("bpi_smartschool_rombel_peminatan", JSON.stringify(classMap));
      } catch (e) {
        console.error("Failed to save rombel peminatan mapping:", e);
      }
    }
    showToast(message, "success");
  };

  // Handle Excel File Selection
  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setImportFile(file);
    setIsParsingExcel(true);
    try {
      const parsed = await parseFinalGradesExcelFile(file);
      setImportRows(parsed);
      showToast(`Berhasil membaca ${parsed.length} baris dari file Excel. Silakan tinjau sebelum disimpan.`, "info");
    } catch (err: any) {
      console.error(err);
      showToast(err.message || "Gagal membaca file Excel. Pastikan format kolom sesuai.", "error");
      setImportRows(null);
    } finally {
      setIsParsingExcel(false);
    }
  };

  // Handle Commit Import to Records
  const handleCommitImport = () => {
    if (!importRows || importRows.length === 0) return;

    let updatedCount = 0;
    let addedCount = 0;
    const newRecordsList = [...sklRecords];

    importRows.forEach((row) => {
      if (!row.isValid) return; // Skip invalid rows

      const existingIndex = newRecordsList.findIndex(
        (r) => r.nis.trim() === row.nis.trim()
      );

      if (existingIndex >= 0) {
        // Update existing record's grades and average
        newRecordsList[existingIndex] = {
          ...newRecordsList[existingIndex],
          fullName: row.fullName || newRecordsList[existingIndex].fullName,
          className: row.className || newRecordsList[existingIndex].className,
          peminatanPaket: row.peminatanPaket || newRecordsList[existingIndex].peminatanPaket,
          status: row.status,
          subjectScores: row.subjectScores,
          overallAverage: row.overallAverage,
        };
        updatedCount++;
      } else {
        // Add new record
        const nextSeq = sklConfig.startingNumber + newRecordsList.length;
        const letterNum = generateLetterNumber(
          sklConfig.letterNumberFormat,
          nextSeq,
          sklConfig.academicYear
        );

        const newRec: SKLRecord = {
          id: `skl-imp-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
          studentId: `std-imp-${row.nis}`,
          letterNumber: letterNum,
          fullName: row.fullName,
          birthPlace: "Bandung",
          birthDate: "01 Januari 2008",
          parentName: "Orang Tua Siswa",
          nis: row.nis,
          nisn: row.nisn || `008${row.nis}`,
          className: row.className || "XII-1",
          peminatanPaket: row.peminatanPaket || `${row.className} / Reguler`,
          status: row.status,
          subjectScores: row.subjectScores,
          overallAverage: row.overallAverage,
        };
        newRecordsList.push(newRec);
        addedCount++;
      }
    });

    saveRecords(newRecordsList);
    setIsImportModalOpen(false);
    setImportRows(null);
    setImportFile(null);
    showToast(
      `Sukses mengimpor nilai akhir! (${updatedCount} siswa diperbarui, ${addedCount} siswa ditambahkan). Terintegrasi langsung dengan SKL.`,
      "success"
    );
  };

  // Helper to extract score for table display
  const getSubjectScoreValue = (rec: SKLRecord, code: string) => {
    const item = rec.subjectScores.find((s) => s.code === code);
    return item != null ? item.score : null;
  };

  const activePrintRecord =
    printingRecord || previewRecord || filteredRecords[0] || sklRecords[0] || null;

  return (
    <>
      {/* Toast Notification */}
      {toast.show && (
        <Toast
          message={toast.message}
          variant={toast.type}
          onClose={() => setToast({ ...toast, show: false })}
        />
      )}

      {/* ======================================================== */}
      {/* 1. DASHBOARD REKAP NILAI AKHIR (DISEMBUNYIKAN SAAT CETAK) */}
      {/* ======================================================== */}
      <div className="space-y-6 print:hidden">

      {/* Breadcrumb Navigation */}
      <div className="flex items-center gap-2 text-xs text-slate-500">
        <Link href="/" className="hover:text-brand-blue">
          Dashboard
        </Link>
        <ChevronRight className="w-3.5 h-3.5" />
        <Link href="/kurikulum" className="hover:text-brand-blue">
          Kurikulum
        </Link>
        <ChevronRight className="w-3.5 h-3.5" />
        <span className="text-slate-800 font-semibold">Nilai Akhir Kelas XII</span>
      </div>

      {/* Page Header */}
      <PageHeader
        title="Rekap Nilai Akhir Kelas XII"
        description="Kelola rekapitulasi nilai ujian sekolah 14 mata pelajaran Kurikulum Merdeka + mapel pilihan tingkat XII, impor massal via file Excel, dan integrasi instan ke pencetakan Surat Keterangan Lulus (SKL)."
        actions={
          <div className="flex flex-wrap items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              leftIcon={<GraduationCap className="w-4 h-4 text-brand-blue" />}
              onClick={() => setIsPeminatanModalOpen(true)}
            >
              Atur Peminatan Kelas
            </Button>
            <Button
              variant="outline"
              size="sm"
              leftIcon={<Sliders className="w-4 h-4 text-brand-blue" />}
              onClick={() => setIsPaperSettingsOpen(true)}
            >
              Pengaturan Kertas & Cetak
            </Button>
            <Button
              variant="outline"
              size="sm"
              leftIcon={<Download className="w-4 h-4" />}
              onClick={() =>
                downloadFinalGradesTemplateXLSX(selectedClass, filteredRecords)
              }
            >
              Unduh Template (.xlsx)
            </Button>
            <Button
              variant="secondary"
              size="sm"
              leftIcon={<Upload className="w-4 h-4" />}
              onClick={() => setIsImportModalOpen(true)}
            >
              Import Nilai Excel
            </Button>
            <Link href="/kurikulum/skl">
              <Button
                variant="primary"
                size="sm"
                leftIcon={<Award className="w-4 h-4" />}
              >
                Ke Modul SKL
              </Button>
            </Link>
          </div>
        }
      />

      {/* Info Banner: Sumber Data Utama SKL */}
      <div className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/80 rounded-2xl flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div className="flex items-start gap-3">
          <div className="w-10 h-10 rounded-xl bg-blue-600 text-white flex items-center justify-center shrink-0 shadow-sm shadow-blue-200">
            <FileSpreadsheet className="w-5 h-5" />
          </div>
          <div>
            <h4 className="text-sm font-bold text-blue-950 flex items-center gap-2">
              Sumber Data Utama Surat Keterangan Lulus (SKL)
              <Badge variant="info" size="sm">
                Real-Time Sync
              </Badge>
            </h4>
            <p className="text-xs text-blue-800/85 mt-0.5 max-w-3xl leading-relaxed">
              Seluruh data nilai di halaman ini tersinkronisasi dua arah secara otomatis dengan generator SKL SMA BPI 1 Bandung. Anda dapat langsung mengedit nilai, mempratinjau blangko resmi A4, dan mencetak SKL siswa tanpa perlu berpindah modul.
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <Link href="/kurikulum/skl">
            <Button
              variant="outline"
              size="sm"
              className="bg-white hover:bg-blue-50 border-blue-300 text-blue-800 text-xs"
              rightIcon={<ArrowRight className="w-3.5 h-3.5" />}
            >
              Kelola Format SKL & TTD
            </Button>
          </Link>
        </div>
      </div>

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          title="Total Siswa Kelas XII"
          value={stats.total}
          icon={Users}
          variant="primary"
          description={
            selectedClass === "Semua"
              ? "Seluruh rombel angkatan XII"
              : `Terdata di ${selectedClass}`
          }
        />
        <StatCard
          title="Rata-Rata Angkatan"
          value={stats.totalScored > 0 ? formatIndonesianScore(stats.average) : "-"}
          icon={TrendingUp}
          variant="purple"
          description={
            stats.totalScored > 0
              ? `Dari ${stats.totalScored} siswa tuntas dinilai`
              : "Belum ada nilai yang diinput"
          }
        />
        <StatCard
          title="Tingkat Kelulusan"
          value={stats.totalScored > 0 ? `${stats.passRate}%` : "-"}
          icon={CheckCircle}
          variant="success"
          description={
            stats.totalScored > 0
              ? `${stats.passCount} dari ${stats.totalScored} siswa memenuhi syarat`
              : "Menunggu penginputan nilai"
          }
        />
        <StatCard
          title="Rentang Nilai Tertinggi"
          value={stats.totalScored > 0 ? formatIndonesianScore(stats.maxScore) : "-"}
          icon={Award}
          variant="neutral"
          description={
            stats.totalScored > 0
              ? `Terendah: ${formatIndonesianScore(stats.minScore)}`
              : "Belum ada nilai yang diinput"
          }
        />
      </div>

      {/* Filters and Search Bar */}
      <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm space-y-3">
        <div className="flex flex-col md:flex-row items-stretch md:items-center justify-between gap-3">
          {/* Class Filter */}
          <div className="flex flex-wrap items-center gap-2">
            <div className="w-48">
              <Select
                value={selectedClass}
                onChange={(e) => {
                  setSelectedClass(e.target.value);
                  setCurrentPage(1);
                }}
                options={CLASS_OPTIONS}
                size="sm"
              />
            </div>

            <div className="w-40">
              <Select
                value={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value);
                  setCurrentPage(1);
                }}
                options={[
                  { label: "Semua Status", value: "Semua" },
                  { label: "Status Lulus", value: "LULUS" },
                  { label: "Tidak Lulus", value: "TIDAK LULUS" },
                  { label: "Belum Ada Nilai", value: "BELUM_DINILAI" },
                ]}
                size="sm"
              />
            </div>

            {(selectedClass !== "Semua" || statusFilter !== "Semua" || searchQuery) && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  setSelectedClass("Semua");
                  setStatusFilter("Semua");
                  setSearchQuery("");
                  setCurrentPage(1);
                }}
                className="text-xs text-slate-500 hover:text-slate-800"
              >
                Reset Filter
              </Button>
            )}
          </div>

          {/* Search Bar */}
          <div className="flex items-center gap-2">
            <div className="w-72">
              <Input
                placeholder="Cari Nama, NIS, atau NISN..."
                value={searchQuery}
                onChange={(e) => {
                  setSearchQuery(e.target.value);
                  setCurrentPage(1);
                }}
                leftIcon={<Search className="w-4 h-4 text-slate-400" />}
                size="sm"
              />
            </div>
          </div>
        </div>

        {/* Quick Legend / Info Bar */}
        <div className="flex flex-wrap items-center justify-between text-[11px] text-slate-500 pt-2 border-t border-slate-100">
          <div className="flex items-center gap-4">
            <span className="flex items-center gap-1.5">
              <span className="w-2.5 h-2.5 rounded-full bg-emerald-500 inline-block"></span>
              Nilai &ge; 85 (Sangat Baik)
            </span>
            <span className="flex items-center gap-1.5">
              <span className="w-2.5 h-2.5 rounded-full bg-blue-500 inline-block"></span>
              Nilai 75 - 84 (Baik)
            </span>
            <span className="flex items-center gap-1.5">
              <span className="w-2.5 h-2.5 rounded-full bg-amber-500 inline-block"></span>
              Nilai &lt; 75 (Perlu Perhatian)
            </span>
          </div>
          <div>
            Menampilkan <strong>{paginatedRecords.length}</strong> dari <strong>{filteredRecords.length}</strong> data siswa
          </div>
        </div>
      </div>

      {/* Table Rekap Nilai Akhir (Scrollable & Sticky) */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
        {paginatedRecords.length === 0 ? (
          <div className="p-8">
            <EmptyState
              title="Tidak ada data siswa ditemukan"
              description="Sesuaikan filter kelas atau gunakan fitur Import Excel untuk memasukkan daftar nilai akhir kelas XII."
              icon={FileBarChart}
              actionText="Import Nilai Excel"
              onAction={() => setIsImportModalOpen(true)}
            />
          </div>
        ) : (
          <div className="overflow-x-auto max-w-full">
            <table className="w-full text-left border-collapse text-xs">
              <thead className="bg-slate-100/80 text-slate-700 font-bold border-b border-slate-200 select-none">
                <tr>
                  {/* Sticky Columns Left */}
                  <th className="sticky left-0 z-20 bg-slate-100 px-3 py-3 w-12 text-center border-r border-slate-200">
                    NO
                  </th>
                  <th className="sticky left-12 z-20 bg-slate-100 px-3 py-3 w-28 border-r border-slate-200">
                    NIS
                  </th>
                  <th className="sticky left-40 z-20 bg-slate-100 px-3 py-3 w-28 border-r border-slate-200">
                    NISN
                  </th>
                  <th className="sticky left-68 z-20 bg-slate-100 px-4 py-3 min-w-[200px] border-r border-slate-200 shadow-[2px_0_5px_rgba(0,0,0,0.04)]">
                    NAMA SISWA
                  </th>
                  <th className="px-3 py-3 min-w-[130px] border-r border-slate-200">
                    KELAS & PEMINATAN
                  </th>

                  {/* Subject Columns */}
                  {SUBJECT_COLUMNS.map((col) => (
                    <th
                      key={col.key}
                      title={col.label}
                      className="px-2.5 py-3 text-center min-w-[70px] border-r border-slate-200 whitespace-nowrap"
                    >
                      <div className="font-bold text-[11px]">{col.short}</div>
                      <div className="text-[9px] font-normal text-slate-500 truncate max-w-[65px]">
                        {col.key}
                      </div>
                    </th>
                  ))}

                  {/* Summary Columns */}
                  <th className="px-3 py-3 text-center min-w-[90px] border-r border-slate-200 bg-blue-50/60 text-blue-900 font-bold">
                    RATA-RATA
                  </th>
                  <th className="px-3 py-3 text-center min-w-[100px] border-r border-slate-200 font-bold">
                    STATUS
                  </th>

                  {/* Sticky Right Action Column */}
                  <th className="sticky right-0 z-20 bg-slate-100 px-3 py-3 text-center min-w-[100px] shadow-[-2px_0_5px_rgba(0,0,0,0.04)] border-l border-slate-200">
                    AKSI
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 text-slate-700">
                {paginatedRecords.map((rec, idx) => {
                  const absoluteIdx = (currentPage - 1) * itemsPerPage + idx + 1;
                  const isPass = rec.status === "LULUS";

                  return (
                    <tr
                      key={rec.id}
                      className="hover:bg-blue-50/40 transition-colors group"
                    >
                      {/* Sticky Index */}
                      <td className="sticky left-0 z-10 bg-white group-hover:bg-blue-50/40 px-3 py-2.5 text-center font-mono text-slate-500 border-r border-slate-200">
                        {absoluteIdx}
                      </td>

                      {/* Sticky NIS */}
                      <td className="sticky left-12 z-10 bg-white group-hover:bg-blue-50/40 px-3 py-2.5 font-mono font-medium text-slate-800 border-r border-slate-200">
                        {rec.nis}
                      </td>

                      {/* Sticky NISN */}
                      <td className="sticky left-40 z-10 bg-white group-hover:bg-blue-50/40 px-3 py-2.5 font-mono text-slate-600 border-r border-slate-200">
                        {rec.nisn}
                      </td>

                      {/* Sticky Student Name */}
                      <td className="sticky left-68 z-10 bg-white group-hover:bg-blue-50/40 px-4 py-2.5 font-semibold text-slate-900 border-r border-slate-200 shadow-[2px_0_5px_rgba(0,0,0,0.04)] whitespace-nowrap">
                        <div className="flex items-center gap-2">
                          <div className="w-6 h-6 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center font-bold text-[10px] shrink-0">
                            {rec.fullName.charAt(0)}
                          </div>
                          <span className="truncate max-w-[180px]">{rec.fullName}</span>
                        </div>
                      </td>

                      {/* Class and Peminatan */}
                      <td className="px-3 py-2.5 border-r border-slate-200 whitespace-nowrap">
                        <div className="font-semibold text-slate-800">{rec.className}</div>
                        <div className="text-[10px] text-slate-500 truncate max-w-[120px]">
                          {rec.peminatanPaket}
                        </div>
                      </td>

                      {/* Subject Scores */}
                      {SUBJECT_COLUMNS.map((col) => {
                        const score = getSubjectScoreValue(rec, col.key);
                        const hasScore = score != null && score > 0;
                        let badgeColor = "text-slate-700 font-mono";
                        if (hasScore) {
                          if (score >= 85) badgeColor = "text-emerald-700 font-bold font-mono";
                          else if (score >= 75) badgeColor = "text-blue-700 font-medium font-mono";
                          else badgeColor = "text-amber-700 font-bold font-mono";
                        }

                        return (
                          <td
                            key={col.key}
                            className="px-2.5 py-2.5 text-center border-r border-slate-100 font-mono"
                          >
                            {hasScore ? (
                              <span className={badgeColor}>
                                {formatIndonesianScore(score)}
                              </span>
                            ) : (
                              <span className="text-slate-300 font-mono">-</span>
                            )}
                          </td>
                        );
                      })}

                      {/* Rata-Rata */}
                      <td className="px-3 py-2.5 text-center border-r border-slate-200 bg-blue-50/40 font-bold font-mono text-sm text-blue-900">
                        {rec.overallAverage > 0 ? (
                          <span className="px-2 py-0.5 rounded-md bg-blue-100 text-blue-950">
                            {formatIndonesianScore(rec.overallAverage)}
                          </span>
                        ) : (
                          <span className="text-slate-400 font-normal text-xs">-</span>
                        )}
                      </td>

                      {/* Status */}
                      <td className="px-3 py-2.5 text-center border-r border-slate-200 whitespace-nowrap">
                        {rec.overallAverage > 0 ? (
                          <Badge variant={isPass ? "success" : "danger"} size="sm">
                            {rec.status}
                          </Badge>
                        ) : (
                          <Badge variant="neutral" size="sm">
                            Belum Ada Nilai
                          </Badge>
                        )}
                      </td>

                      {/* Sticky Right Action Buttons (Hanya 2 Aksi: Edit & Pratinjau) */}
                      <td className="sticky right-0 z-10 bg-white group-hover:bg-blue-50/40 px-3 py-2 text-center shadow-[-2px_0_5px_rgba(0,0,0,0.04)] border-l border-slate-200 whitespace-nowrap">
                        <div className="flex items-center justify-center gap-1.5">
                          <button
                            type="button"
                            title="Edit Nilai Akhir"
                            onClick={() => setEditRecord(rec)}
                            className="p-1.5 rounded-lg text-slate-600 hover:text-blue-700 hover:bg-blue-100 transition-colors"
                          >
                            <Edit3 className="w-4 h-4" />
                          </button>
                          <button
                            type="button"
                            title="Pratinjau SKL"
                            onClick={() => setPreviewRecord(rec)}
                            className="p-1.5 rounded-lg text-slate-600 hover:text-emerald-700 hover:bg-emerald-100 transition-colors"
                          >
                            <Eye className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {/* Table Footer with Pagination */}
        {filteredRecords.length > 0 && (
          <div className="p-4 border-t border-slate-200 flex flex-col sm:flex-row items-center justify-between gap-3 bg-slate-50/50">
            <span className="text-xs text-slate-500">
              Menampilkan {paginatedRecords.length} dari {filteredRecords.length} siswa kelas XII terdaftar
            </span>
            <Pagination
              currentPage={currentPage}
              totalItems={filteredRecords.length}
              itemsPerPage={itemsPerPage}
              onPageChange={setCurrentPage}
            />
          </div>
        )}
      </div>
      </div>

      {/* ======================================================== */}
      {/* 2. MODAL DIALOGS (DISEMBUNYIKAN SAAT PENCETAKAN)         */}
      {/* ======================================================== */}
      <div className="print:hidden">
        {/* MODAL 1: IMPORT NILAI AKHIR VIA EXCEL (.XLSX) */}
        <Modal
          isOpen={isImportModalOpen}
          onClose={() => {
            setIsImportModalOpen(false);
            setImportRows(null);
            setImportFile(null);
          }}
          title="Import Nilai Akhir Kelas XII (.xlsx)"
          description="Unggah file spreadsheet Excel berisi data nilai ujian sekolah kelas XII sesuai format kolom Kurikulum Merdeka."
          maxWidth="max-w-4xl"
        >
          <div className="space-y-4 text-xs">
            {/* File Upload Box */}
            <div className="border-2 border-dashed border-slate-300 rounded-2xl p-6 text-center hover:border-brand-blue bg-slate-50/50 transition-colors">
              <input
                type="file"
                ref={fileInputRef}
                accept=".xlsx, .xls"
                onChange={handleFileChange}
                className="hidden"
              />
              <div className="flex flex-col items-center justify-center space-y-2">
                <div className="w-12 h-12 rounded-full bg-blue-100 text-brand-blue flex items-center justify-center">
                  <FileSpreadsheet className="w-6 h-6" />
                </div>
                <div>
                  <p className="text-sm font-bold text-slate-800">
                    {importFile ? importFile.name : "Klik atau Seret file Excel (.xlsx) ke sini"}
                  </p>
                  <p className="text-slate-500 text-[11px] mt-0.5">
                    Format didukung: Microsoft Excel Worksheet (.xlsx, .xls)
                  </p>
                </div>
                <div className="pt-2 flex items-center gap-2">
                  <Button
                    type="button"
                    variant="primary"
                    size="sm"
                    onClick={() => fileInputRef.current?.click()}
                    leftIcon={<Upload className="w-3.5 h-3.5" />}
                  >
                    Pilih File Excel
                  </Button>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => downloadFinalGradesTemplateXLSX(selectedClass, filteredRecords)}
                    leftIcon={<Download className="w-3.5 h-3.5" />}
                  >
                    Unduh Format Contoh
                  </Button>
                </div>
              </div>
            </div>

            {/* Parsing Spinner */}
            {isParsingExcel && (
              <div className="p-4 text-center text-slate-500 flex items-center justify-center gap-2">
                <RefreshCw className="w-4 h-4 animate-spin text-brand-blue" />
                <span>Memvalidasi struktur kolom dan nilai ujian siswa...</span>
              </div>
            )}

            {/* Import Preview Table */}
            {importRows && importRows.length > 0 && (
              <div className="space-y-3">
                <div className="flex items-center justify-between p-3 bg-blue-50 border border-blue-200 rounded-xl">
                  <div>
                    <h4 className="font-bold text-blue-900 text-xs">
                      Pratinjau Validasi Data ({importRows.length} Siswa Ditemukan)
                    </h4>
                    <p className="text-[11px] text-blue-700 mt-0.5">
                      {importRows.filter((r) => r.isValid).length} baris valid dan siap disinkronkan ke sistem nilai &amp; SKL.
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant="success" size="sm">
                      {importRows.filter((r) => r.isValid).length} Valid
                    </Badge>
                    {importRows.filter((r) => !r.isValid).length > 0 && (
                      <Badge variant="danger" size="sm">
                        {importRows.filter((r) => !r.isValid).length} Bermasalah
                      </Badge>
                    )}
                  </div>
                </div>

                <div className="max-h-64 overflow-y-auto border border-slate-200 rounded-xl">
                  <table className="w-full text-left text-xs border-collapse">
                    <thead className="bg-slate-100 text-slate-700 sticky top-0 font-bold border-b border-slate-200">
                      <tr>
                        <th className="p-2 w-10 text-center">NO</th>
                        <th className="p-2 w-24">NIS</th>
                        <th className="p-2">NAMA SISWA</th>
                        <th className="p-2 w-16 text-center">KELAS</th>
                        <th className="p-2 w-20 text-center">RATA-RATA</th>
                        <th className="p-2 w-20 text-center">STATUS</th>
                        <th className="p-2 w-24 text-center">VALIDASI</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {importRows.map((row, idx) => (
                        <tr
                          key={row.id}
                          className={row.isValid ? "hover:bg-slate-50" : "bg-rose-50/50"}
                        >
                          <td className="p-2 text-center font-mono">{idx + 1}</td>
                          <td className="p-2 font-mono font-medium">{row.nis}</td>
                          <td className="p-2 font-medium">{row.fullName}</td>
                          <td className="p-2 text-center">{row.className}</td>
                          <td className="p-2 text-center font-mono font-bold text-blue-900">
                            {formatIndonesianScore(row.overallAverage)}
                          </td>
                          <td className="p-2 text-center">
                            <Badge
                              variant={row.status === "LULUS" ? "success" : "danger"}
                              size="sm"
                            >
                              {row.status}
                            </Badge>
                          </td>
                          <td className="p-2 text-center">
                            {row.isValid ? (
                              <span className="inline-flex items-center gap-1 text-[11px] text-emerald-600 font-semibold">
                                <CheckCircle className="w-3.5 h-3.5" /> Siap
                              </span>
                            ) : (
                              <span
                                className="inline-flex items-center gap-1 text-[11px] text-rose-600 font-semibold cursor-help"
                                title={row.errors.join(", ")}
                              >
                                <AlertCircle className="w-3.5 h-3.5" /> Error
                              </span>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* Modal Action Buttons */}
            <div className="flex items-center justify-end gap-2 pt-3 border-t border-slate-200">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => {
                  setIsImportModalOpen(false);
                  setImportRows(null);
                  setImportFile(null);
                }}
              >
                Batal
              </Button>
              <Button
                type="button"
                variant="primary"
                size="sm"
                disabled={!importRows || importRows.filter((r) => r.isValid).length === 0}
                onClick={handleCommitImport}
                leftIcon={<CheckCircle className="w-4 h-4" />}
              >
                Terapkan &amp; Simpan Nilai ({importRows ? importRows.filter((r) => r.isValid).length : 0})
              </Button>
            </div>
          </div>
        </Modal>

        {/* MODAL 2: PRATINJAU SKL (INTEGRASI LANGSUNG) */}
        {previewRecord && (
          <SKLPreviewModal
            isOpen={!!previewRecord}
            onClose={() => setPreviewRecord(null)}
            record={previewRecord}
            config={sklConfig}
            onConfigChange={handleSaveConfig}
            onPrint={() => handlePrintStudent(previewRecord)}
          />
        )}

        {/* MODAL 3: EDIT NILAI AKHIR MANUAL SISWA */}
        {editRecord && (
          <SKLEditModal
            isOpen={!!editRecord}
            onClose={() => setEditRecord(null)}
            record={editRecord}
            onSave={handleSaveEdit}
          />
        )}

        {/* MODAL 4: PENGATURAN KERTAS & CETAK */}
        <SKLPaperSettingsModal
          isOpen={isPaperSettingsOpen}
          onClose={() => setIsPaperSettingsOpen(false)}
          paperSettings={sklConfig.paperSettings || DEFAULT_PAPER_SETTINGS}
          onSave={handleSavePaperSettings}
        />

        {/* MODAL 5: ATUR PEMINATAN / PAKET KELAS (1 KLIK) */}
        <SKLPeminatanModal
          isOpen={isPeminatanModalOpen}
          onClose={() => setIsPeminatanModalOpen(false)}
          sklRecords={sklRecords}
          initialClass={selectedClass}
          onApplyPeminatan={handleApplyPeminatan}
        />
      </div>

      {/* ======================================================== */}
      {/* 3. AREA KHUSUS PENCETAKAN (HANYA DOKUMEN INI YG TERCETAK) */}
      {/* ======================================================== */}
      <div id="skl-single-print-area" className="printable-document printable-area hidden print:block w-full">
        {activePrintRecord && (
          <SKLDocumentSheet
            record={activePrintRecord}
            config={sklConfig}
            isPrintMode={true}
          />
        )}
      </div>

      {/* Style Print khusus untuk memastikan HANYA blangko SKL yang tercetak dalam format A4/F4 Portrait */}
      <style
        dangerouslySetInnerHTML={{
          __html: `
            @media print {
              @page {
                size: 215mm 330mm;
                margin: 10mm 12mm 10mm 12mm;
              }
              html, body {
                background: #ffffff !important;
                color: #000000 !important;
                overflow: visible !important;
                width: 100% !important;
                height: auto !important;
                margin: 0 !important;
                padding: 0 !important;
              }
              /* Sembunyikan seluruh dashboard, navigasi, topbar, dan modal dialog */
              .print\\:hidden,
              .print-hidden,
              [role="dialog"],
              aside,
              header,
              nav {
                display: none !important;
              }
              /* Hanya tampilkan lembar SKL resmi */
              #skl-single-print-area,
              #skl-single-print-area *,
              #skl-document-sheet,
              #skl-document-sheet * {
                visibility: visible !important;
              }
              #skl-single-print-area {
                display: block !important;
                width: 100% !important;
                max-width: 100% !important;
                margin: 0 !important;
                padding: 0 !important;
                box-sizing: border-box !important;
                page-break-inside: avoid !important;
                break-inside: avoid !important;
              }
              #skl-single-print-area * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
              }
            }
          `,
        }}
      />
    </>
  );
}

