import { prisma } from "@/lib/prisma";
import { notFound } from "next/navigation";
import { PrintButton } from "./print-button";

interface PageProps {
  params: Promise<{ id: string }>;
}

export default async function SklPrintPage({ params }: PageProps) {
  const { id } = await params;

  // Fetch Student & Grades
  const siswa = await prisma.siswa.findUnique({
    where: { id },
    include: {
      nilaiSKL: true,
      rombel: true,
    },
  });

  if (!siswa || !siswa.nilaiSKL) {
    return notFound();
  }

  // Fetch Settings (Active Year or Year of Student? Use latest for now)
  const setting = await prisma.settingSKL.findFirst({
    orderBy: { createdAt: "desc" },
  });

  if (!setting) {
    return <div>Pengaturan SKL belum dibuat.</div>;
  }

  // Format Helper
  const formatDate = (dateStr?: string | null) => {
    if (!dateStr) return "";
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr; // Return original if not parseable (e.g. manual text)

      return new Intl.DateTimeFormat("id-ID", {
        day: "numeric",
        month: "long",
        year: "numeric",
      }).format(date);
    } catch (e) {
      return dateStr;
    }
  };

  // Replace placeholders in rich text
  const replaceTags = (text: string) => {
    let content = text;
    content = content.replace(/{NAMA}/g, `<b>${siswa.nama}</b>`);
    content = content.replace(/{NISN}/g, siswa.nisn || "-");
    content = content.replace(/{NIS}/g, siswa.nis);
    content = content.replace(/{KELAS}/g, siswa.rombel?.namaRombel || "-");
    content = content.replace(/{STATUS}/g, `<b>${siswa.nilaiSKL?.status || "LULUS"}</b>`);
    return content;
  };

  // Parse Grades
  const nilaiRapor = (siswa.nilaiSKL.nilaiRapor as Record<string, number>) || {};
  const nilaiUjian = (siswa.nilaiSKL.nilaiUjian as Record<string, number>) || {};

  // Combine subjects (Union of keys)
  const subjects = Array.from(new Set([...Object.keys(nilaiRapor), ...Object.keys(nilaiUjian)]));

  const schoolSettings = await prisma.settingSekolah.findFirst();

  console.log(schoolSettings);

  return (
    <div className="relative mx-auto min-h-screen max-w-[210mm] bg-white p-8 font-serif text-sm leading-relaxed text-black print:p-0">
      {/* Print Trigger */}
      <PrintButton />

      {/* Watermark */}
      {(schoolSettings?.logo || setting.headerImage) && (
        <div className="pointer-events-none absolute inset-0 z-0 flex items-center justify-center overflow-hidden">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={schoolSettings?.logo || setting.headerImage || ""}
            alt="Watermark"
            className="w-[400px] opacity-10"
          />
        </div>
      )}

      <div className="relative z-10">
        {/* Header */}
        <div className="mb-2">
          {setting.headerImage || schoolSettings?.headerLaporan ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={setting.headerImage || schoolSettings?.headerLaporan || ""}
              alt="Kop Surat"
              className="h-auto max-h-[200px] w-full object-contain"
            />
          ) : (
            <div className="flex items-center justify-between">
              {/* Left Logo */}
              <div className="flex w-24 justify-center">
                {schoolSettings?.logo && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={schoolSettings.logo} alt="Logo Kiri" className="h-24 w-auto object-contain" />
                )}
              </div>

              {/* Center Text */}
              <div className="flex-1 text-center">
                <h3 className="text-sm font-bold uppercase">
                  {schoolSettings?.kementrian || "KEMENTERIAN PENDIDIKAN DASAR DAN MENENGAH"}
                </h3>
                <h3 className="text-sm font-bold uppercase">DINAS PENDIDIKAN</h3>
                <h1 className="mt-1 text-2xl font-bold uppercase">
                  {schoolSettings?.namaSekolah || "SMA NEGERI NUSANTARA"}
                </h1>
                <p className="font-bold">TERAKREDITASI "A"</p>
                <p className="font-bold">NPSN: {schoolSettings?.npsn || "-"}</p>
                <p className="mt-1 text-xs">
                  Alamat: {schoolSettings?.alamat} {schoolSettings?.kabupaten} Kode Pos: -
                </p>
                <p className="text-xs">Website: - Email: {schoolSettings?.email}</p>
              </div>

              {/* Right Logo */}
              <div className="flex w-24 justify-center">
                {schoolSettings?.logoKanan && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={schoolSettings.logoKanan} alt="Logo Kanan" className="h-24 w-auto object-contain" />
                )}
              </div>
            </div>
          )}
        </div>

        <div className="mt-0 mb-4 text-center">
          <h1 className="mb-1 text-xl font-bold uppercase underline">SURAT KETERANGAN LULUS</h1>
          <p className="font-bold">No. Surat : {siswa.nilaiSKL?.nomorSurat || setting.nomorSurat}</p>
        </div>

        {/* Pembuka */}
        <div
          className="mb-4 pr-9 pl-9 text-justify"
          dangerouslySetInnerHTML={{ __html: replaceTags(setting.pembuka) }}
        />

        {/* Identitas */}
        <div className="mb-4 pr-16 pl-16">
          <table className="w-full">
            <tbody>
              <tr>
                <td className="w-48 py-1">Nama</td>
                <td className="py-1">
                  : <b>{siswa.nama}</b>
                </td>
              </tr>
              <tr>
                <td className="py-1">Tempat, Tgl Lahir</td>
                <td className="py-1">: -</td>
              </tr>
              <tr>
                <td className="py-1">Nomor Induk Peserta Didik</td>
                <td className="py-1">: {siswa.nis}</td>
              </tr>
              <tr>
                <td className="py-1">Nomor Induk Siswa Nasional</td>
                <td className="py-1">: {siswa.nisn || "-"}</td>
              </tr>
              <tr>
                <td className="py-1">Kompetensi Keahlian</td>
                <td className="py-1">: {siswa.rombel?.namaRombel || "-"}</td>
              </tr>
            </tbody>
          </table>
        </div>

        {/* Isi (Statement) */}
        <div className="mb-4 pr-9 pl-9 text-justify" dangerouslySetInnerHTML={{ __html: replaceTags(setting.isi) }} />

        {/* LULUS Header (Optional, user image showed "LULUS" center big) */}
        <div className="my-3 text-center">
          <h2 className="text-2xl font-bold tracking-widest uppercase">{siswa.nilaiSKL?.status || "LULUS"}</h2>
        </div>

        {/* Tabel Nilai (Simplified based on user image "MATA PELAJARAN | NILAI") */}
        <div className="mb-6 px-12">
          <p className="mb-2">Dengan hasil sebagai berikut:</p>
          <table className="w-full border-collapse border border-black text-sm">
            <thead>
              <tr>
                <th className="border border-black bg-transparent px-4 py-2 text-left">MATA PELAJARAN</th>
                <th className="w-24 border border-black bg-transparent px-4 py-2 text-center">NILAI</th>
              </tr>
            </thead>
            <tbody>
              {/* Normally listing all subjects. For summary, maybe just average? 
                    User image shows "RATA-RATA NILAI | 0.00".
                    If user uploaded Detail Grades, we list them or just the Summary?
                    The table in previous step listed all mapels. I'll keep listing all mapels efficiently.
                */}
              {subjects.map((sub) => {
                // Start simplified: Just Rata-Rata of Rapor+Ujian? Or just Ujian?
                // User template had Rapor & Ujian columns.
                // Image shows One "NILAI" column.
                // I will take the Average of Rapor & Ujian if both exist, or just whatever is uploaded.
                // Let's stick to listing subjects.
                const valRapor = nilaiRapor[sub] || 0;
                const valUjian = nilaiUjian[sub] || 0;
                const finalVal = valUjian > 0 ? valUjian : valRapor; // Prefer Ujian or Average?
                // Let's just output valUjian for SKL usually.
                return (
                  <tr key={sub}>
                    <td className="border border-black px-4 py-1 uppercase">{sub}</td>
                    <td className="border border-black px-4 py-1 text-center font-bold">{finalVal.toFixed(2)}</td>
                  </tr>
                );
              })}
              <tr className="font-bold">
                <td className="border border-black px-4 py-2 uppercase">RATA-RATA NILAI</td>
                <td className="border border-black px-4 py-2 text-center">
                  {siswa.nilaiSKL.rataRata?.toFixed(2) || "0.00"}
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        {/* Penutup */}
        <div
          className="mb-8 pr-9 pl-9 text-justify"
          dangerouslySetInnerHTML={{ __html: replaceTags(setting.penutup) }}
        />

        {/* Footer / TTD */}
        <div className="mt-12 flex justify-end pr-10">
          <div className="relative min-w-[300px] text-left">
            <p className="mb-0">
              {schoolSettings?.kabupaten || "Kabupaten"}, {setting.tanggalSurat || formatDate(new Date().toISOString())}
            </p>
            <p className="font-bold">Kepala Sekolah,</p>

            {/* Signature Space */}
            <div className="relative my-0 flex h-28 w-full items-center">
              {/* Stempel Left - shifted left to overlap text or space */}
              {schoolSettings?.stempel && (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={schoolSettings.stempel}
                  alt="Stempel"
                  className="absolute top-0 left-[-40px] h-32 w-32 rotate-[-5deg] object-contain opacity-80"
                />
              )}
              {/* TTD - overlapping name */}
              {schoolSettings?.ttdKepsek && (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={schoolSettings.ttdKepsek}
                  alt="TTD"
                  className="absolute bottom-[-10px] left-10 z-10 h-28 w-auto object-contain"
                />
              )}
            </div>

            <p className="relative z-20 font-bold uppercase underline">
              {schoolSettings?.kepalaSekolah || "(Nama Kepala Sekolah)"}
            </p>
            <p className="relative z-20">NIP. {schoolSettings?.nipKepalaSekolah || "-"}</p>
          </div>
        </div>
      </div>
    </div>
  );
}
