"use client";

import React, { useRef, useState, useEffect } from "react";
import { Printer, FileText, FileSpreadsheet } from "lucide-react";
import { Modal } from "@/components/ui/Modal";
import { Button } from "@/components/ui/Button";
import { useSchoolOfficials } from "@/hooks/useSchoolOfficials";
import { PrintOrientationToggle } from "@/components/ui/PrintOrientationToggle";
import { triggerPrint, PrintOrientation } from "@/lib/printUtils";
import { CatatanWaliKelasRecord } from "@/lib/db";
import * as XLSX from "xlsx";

interface CatatanWaliKelasPrintModalProps {
  isOpen: boolean;
  onClose: () => void;
  data: CatatanWaliKelasRecord[];
  academicYear: string;
  semester: string;
  className: string;
  homeroomTeacherName: string;
  homeroomTeacherNip?: string | null;
}

export const CatatanWaliKelasPrintModal: React.FC<CatatanWaliKelasPrintModalProps> = ({
  isOpen,
  onClose,
  data = [],
  academicYear,
  semester,
  className,
  homeroomTeacherName,
  homeroomTeacherNip,
}) => {
  const { officials } = useSchoolOfficials();
  const printRef = useRef<HTMLDivElement>(null);
  const [printOrientation, setPrintOrientation] = useState<PrintOrientation>("landscape");

  useEffect(() => {
    if (isOpen) {
      setPrintOrientation("landscape");
    }
  }, [isOpen]);

  const kepalaSekolah =
    officials.find(
      (o) =>
        o.id === "kepala_sekolah" ||
        (o.role_name && o.role_name.toLowerCase().includes("kepala sekolah"))
    ) || {
      name: "Tatang, M.Pd.",
      nip: "NIPY. 10079",
      role_name: "Kepala Sekolah",
    };

  const todayFormatted = new Date().toLocaleDateString("id-ID", {
    day: "numeric",
    month: "long",
    year: "numeric",
  });

  const handlePrint = () => {
    triggerPrint(printOrientation);
  };

  const handleExportExcel = () => {
    if (data.length === 0) return;
    const rows = data.map((item, idx) => ({
      No: idx + 1,
      Tanggal: item.date,
      Kategori: item.category,
      Sasaran: item.target_type,
      "Nama Siswa": item.target_type === "Seluruh Kelas" ? "Seluruh Kelas" : item.student_name || "-",
      NIS: item.target_type === "Seluruh Kelas" ? "-" : item.student_nis || "-",
      "Uraian Catatan / Kejadian": item.notes,
      "Tindak Lanjut": item.follow_up || "-",
      Status: item.status,
      "Wali Kelas": item.homeroom_teacher_name,
      Kelas: item.class_name,
      Semester: item.semester,
      "Tahun Ajaran": item.academic_year,
    }));

    const ws = XLSX.utils.json_to_sheet(rows);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Catatan Wali Kelas");

    const tglExport = new Date().toISOString().split("T")[0];
    const fileName = `Rekap_Catatan_Wali_Kelas_${className}_${academicYear.replace(/[\/\s]/g, "-")}_${semester}_${tglExport}.xlsx`;
    XLSX.writeFile(wb, fileName);
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={`Pratinjau Cetak Catatan Wali Kelas — Kelas ${className} (${academicYear} - Semester ${semester})`}
      maxWidth="2xl"
      hideOnPrint={false}
    >
      <div className="space-y-4">
        {/* Style tag khusus print preview: Standar Folio / F4 (215x330mm) */}
        <style
          dangerouslySetInnerHTML={{
            __html: `
            @page {
              size: ${printOrientation === "landscape" ? "330mm 215mm" : "215mm 330mm"};
              margin: 0 !important;
            }
            @media print {
              @page {
                size: ${printOrientation === "landscape" ? "330mm 215mm" : "215mm 330mm"};
                margin: 0 !important;
              }
              body * {
                visibility: hidden !important;
              }
              #printable-catatan-wali-kelas,
              #printable-catatan-wali-kelas * {
                visibility: visible !important;
              }
              #printable-catatan-wali-kelas {
                position: absolute !important;
                left: 0 !important;
                top: 0 !important;
                width: 100% !important;
                max-width: 100% !important;
                margin: 0 !important;
                padding: 10mm 12mm 10mm 12mm !important;
                box-sizing: border-box !important;
                background: #ffffff !important;
                border: none !important;
                box-shadow: none !important;
                z-index: 9999999 !important;
              }
              html, body {
                width: 100% !important;
                height: auto !important;
                margin: 0 !important;
                padding: 0 !important;
                background: #ffffff !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
              }
            }
          `,
          }}
        />

        {/* Action Bar Header */}
        <div className="flex flex-wrap items-center justify-between gap-3 p-3 bg-slate-50 border border-slate-200 rounded-xl print:hidden">
          <div className="flex items-center gap-2 shrink-0">
            <span className="inline-flex items-center px-2.5 py-1 rounded text-[11px] font-bold bg-blue-50 text-blue-700 border border-blue-200 shrink-0">
              Standar Folio / F4 (215×330 mm)
            </span>
            <span className="text-xs text-slate-500 hidden md:inline">
              Layout Resmi Modul Kurikulum SMA BPI 1 Bandung
            </span>
          </div>

          <div className="flex flex-wrap items-center gap-2 sm:gap-2.5 shrink-0">
            <div className="shrink-0">
              <PrintOrientationToggle
                value={printOrientation}
                onChange={setPrintOrientation}
              />
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={handleExportExcel}
              className="h-9 px-3.5 text-xs font-medium text-emerald-700 border-emerald-300 hover:bg-emerald-50 inline-flex items-center gap-2 whitespace-nowrap shrink-0 shadow-2xs"
              title="Unduh Rekap Catatan (.xlsx)"
            >
              <FileSpreadsheet className="w-4 h-4 text-emerald-600 shrink-0" />
              <span className="whitespace-nowrap">Unduh Excel</span>
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={onClose}
              className="h-9 px-3.5 text-xs font-medium text-slate-700 hover:bg-slate-100 whitespace-nowrap shrink-0 shadow-2xs"
            >
              Tutup
            </Button>
            <Button
              variant="primary"
              size="sm"
              onClick={handlePrint}
              className="h-9 px-4 text-xs font-semibold bg-blue-600 hover:bg-blue-700 text-white inline-flex items-center gap-2 whitespace-nowrap shrink-0 shadow-xs"
            >
              <Printer className="w-4 h-4 shrink-0" />
              <span className="whitespace-nowrap">Cetak Sekarang (PDF)</span>
            </Button>
          </div>
        </div>

        {/* Dokumen Lembar Cetak */}
        <div
          id="printable-catatan-wali-kelas"
          ref={printRef}
          className={`printable-document printable-area print-${printOrientation} bg-white p-7 sm:p-9 border border-slate-200 rounded-xl shadow-xs text-black print:border-none print:shadow-none print:p-0 print:m-0 print:w-full`}
          style={{
            fontFamily: "'Times New Roman', Times, serif",
            lineHeight: 1.35,
          }}
        >
          {/* KOP SURAT RESMI SMA BPI 1 BANDUNG */}
          <div className="w-full pb-1 mb-3">
            <div className="flex items-center justify-between gap-4 pb-2">
              {/* Logo Yayasan BPI Kiri */}
              <div className="w-20 shrink-0 flex items-center justify-center">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src="/images/logo-yayasan-bpi.png"
                  alt="Logo Yayasan BPI"
                  className="w-16 h-auto object-contain block"
                  onError={(e) => {
                    (e.target as HTMLImageElement).src = "/images/logo-ypbpi.png";
                  }}
                />
              </div>

              {/* Teks Kop Surat Tengah */}
              <div className="text-center flex-1 px-2 font-serif text-black leading-tight space-y-0.5">
                <h4 className="text-[13px] sm:text-[14px] font-bold tracking-wider text-slate-900 uppercase">
                  YAYASAN BADAN PERGURUAN INDONESIA
                </h4>
                <h3 className="text-[12px] sm:text-[13px] font-bold tracking-wider text-slate-800 uppercase">
                  SEKOLAH MENENGAH ATAS
                </h3>
                <h1 className="text-[17px] sm:text-[18px] font-extrabold text-slate-950 uppercase tracking-wide">
                  SMA BPI 1 BANDUNG
                </h1>
                <p className="text-[10px] sm:text-[10.5px] text-slate-800 font-semibold">
                  TERAKREDITASI &ldquo;A&rdquo; (UNGGUL) &bull; NSS: 30.0.02.60.13.088 &bull; NPSN: 20219738
                </p>
                <p className="text-[9px] sm:text-[9.5px] text-slate-700 font-normal">
                  Jl. Burangrang No. 8 Telp. (022) 7301739 - Fax. (022) 7305805 Bandung 40262
                </p>
              </div>

              {/* Logo / Teks BPI Kanan */}
              <div className="w-20 shrink-0 flex items-center justify-center">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src="/images/tulisan-bpi.png"
                  alt="Logo BPI"
                  className="w-16 h-auto object-contain block"
                  onError={(e) => {
                    (e.target as HTMLImageElement).src = "/images/logo-bpi.png";
                  }}
                />
              </div>
            </div>

            {/* Garis Pembatas Tebal Ganda Kop Surat */}
            <div className="w-full border-b-[3px] border-double border-slate-950" />
          </div>

          {/* JUDUL DOKUMEN & SUB-METADATA */}
          <div className="text-center my-4 space-y-1">
            <h3 className="text-sm sm:text-base font-bold uppercase underline tracking-wider text-slate-950">
              BUKU CATATAN PEMBINAAN & KONSELING WALI KELAS
            </h3>
            <p className="text-xs text-slate-700 font-semibold">
              Tahun Ajaran {academicYear} &bull; Semester {semester}
            </p>
          </div>

          {/* INFORMASI KELAS & WALI KELAS */}
          <div className="text-xs text-slate-800 mb-4 grid grid-cols-2 gap-2 bg-slate-50/50 p-2.5 rounded-lg border border-slate-200">
            <div>
              <p>
                <span className="font-semibold w-28 inline-block">Rombel / Kelas:</span>
                <span className="font-bold text-slate-950">Kelas {className}</span>
              </p>
              <p>
                <span className="font-semibold w-28 inline-block">Tahun Ajaran:</span>
                <span>{academicYear}</span>
              </p>
            </div>
            <div>
              <p>
                <span className="font-semibold w-28 inline-block">Wali Kelas:</span>
                <span className="font-bold text-slate-950">{homeroomTeacherName}</span>
              </p>
              <p>
                <span className="font-semibold w-28 inline-block">NIP / NIPY:</span>
                <span>{homeroomTeacherNip || "-"}</span>
              </p>
            </div>
          </div>

          {/* TABEL CATATAN WALI KELAS */}
          <div className="w-full overflow-hidden border border-slate-950 rounded-sm mb-6">
            <table className="w-full text-[11px] border-collapse">
              <thead>
                <tr className="bg-slate-100 text-slate-950 font-bold uppercase text-center border-b border-slate-950">
                  <th className="py-2 px-1.5 border-r border-slate-950 w-8">No</th>
                  <th className="py-2 px-2 border-r border-slate-950 w-24">Tanggal</th>
                  <th className="py-2 px-2 border-r border-slate-950 w-32">Kategori</th>
                  <th className="py-2 px-2 border-r border-slate-950 w-28">Sasaran / Siswa</th>
                  <th className="py-2 px-3 border-r border-slate-950 text-left">Uraian Masalah / Materi Pengarahan</th>
                  <th className="py-2 px-3 border-r border-slate-950 text-left w-44">Tindak Lanjut / Solusi</th>
                  <th className="py-2 px-2 text-center w-24">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-400 text-slate-900">
                {data.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="py-8 text-center text-slate-500 italic">
                      Tidak ada catatan pembinaan wali kelas pada filter periode ini.
                    </td>
                  </tr>
                ) : (
                  data.map((item, idx) => (
                    <tr key={item.id} className="align-top hover:bg-slate-50/50">
                      <td className="py-2 px-1.5 text-center font-medium border-r border-slate-400">
                        {idx + 1}
                      </td>
                      <td className="py-2 px-2 border-r border-slate-400 text-center font-mono">
                        {item.date}
                      </td>
                      <td className="py-2 px-2 border-r border-slate-400 font-semibold text-slate-800">
                        {item.category}
                      </td>
                      <td className="py-2 px-2 border-r border-slate-400">
                        {item.target_type === "Seluruh Kelas" ? (
                          <span className="font-bold text-blue-900">Seluruh Kelas</span>
                        ) : (
                          <div>
                            <div className="font-bold text-slate-950">{item.student_name || "-"}</div>
                            {item.student_nis && (
                              <div className="text-[10px] text-slate-500 font-mono">NIS: {item.student_nis}</div>
                            )}
                          </div>
                        )}
                      </td>
                      <td className="py-2 px-3 border-r border-slate-400 text-left leading-relaxed">
                        {item.notes}
                      </td>
                      <td className="py-2 px-3 border-r border-slate-400 text-left leading-relaxed italic">
                        {item.follow_up || "-"}
                      </td>
                      <td className="py-2 px-2 text-center font-semibold">
                        {item.status}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          {/* BLOK TANDA TANGAN DINAMIS (STRICT LAYOUT)
              Sisi Kiri: Tatang, M.Pd. (Kepala SMA BPI 1 Bandung)
              Sisi Kanan: Wali Kelas Pengampu (Dinamis sesuai data kelas) */}
          <div
            className="flex items-start justify-between text-xs text-slate-950 pt-3"
            style={{ pageBreakInside: "avoid" }}
          >
            {/* Sisi Kiri: Mengetahui, Kepala Sekolah */}
            <div className="text-center min-w-[220px]">
              <p className="mb-0.5">Mengetahui,</p>
              <p className="font-bold">Kepala SMA BPI 1 Bandung</p>
              <div className="h-16 flex items-center justify-center">
                <span className="text-[10px] text-slate-400 italic">
                  (Tanda Tangan & Cap Sekolah)
                </span>
              </div>
              <p className="font-bold underline text-slate-950 uppercase">
                {kepalaSekolah.name || "Tatang, M.Pd."}
              </p>
              <p className="font-medium text-slate-700 text-[11px]">
                {kepalaSekolah.nip || "NIPY. 10079"}
              </p>
            </div>

            {/* Sisi Kanan: Tanggal Dinamis & Wali Kelas Dinamis */}
            <div className="text-center min-w-[220px]">
              <p className="mb-0.5">Bandung, {todayFormatted}</p>
              <p className="font-bold">Wali Kelas {className}</p>
              <div className="h-16 flex items-center justify-center">
                <span className="text-[10px] text-slate-400 italic">
                  (Tanda Tangan Wali Kelas)
                </span>
              </div>
              <p className="font-bold underline text-slate-950 uppercase">
                {homeroomTeacherName || "Reni Susanti, S.Pd."}
              </p>
              <p className="font-medium text-slate-700 text-[11px]">
                {homeroomTeacherNip || "NIPY. 10105"}
              </p>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};
