"use client";

import React, { useState, useEffect, useMemo, useCallback } from "react";
import {
  Home,
  CheckSquare,
  Square,
  Search,
  Plus,
  Pencil,
  Trash2,
  Printer,
  X,
  RefreshCw,
  CheckCircle2,
  AlertTriangle,
  ArrowLeft,
  Layers,
  Sparkles,
  ClipboardCheck,
  Calendar,
} from "lucide-react";
import { Modal } from "@/components/ui/Modal";
import { StatCard } from "@/components/ui/StatCard";
import { useSchoolOfficials } from "@/hooks/useSchoolOfficials";
import { useSmartSchool } from "@/context/SmartSchoolContext";
import { getCurrentAcademicYear, getAcademicYearOptions } from "@/lib/academicYear";

export const ACADEMIC_YEARS = getAcademicYearOptions();

export interface ClassroomConditionItem {
  id: number;
  grade_level: string;
  class_name: string;
  item_name: string;
  quantity: number | null;
  is_good: number;
  is_damaged: number;
  notes: string | null;
  follow_up: string | null;
  sort_order: number;
  academic_year?: string;
}

interface ClassroomConditionViewProps {
  gradeLevel: "X" | "XI" | "XII";
}

export const ClassroomConditionView: React.FC<ClassroomConditionViewProps> = ({
  gradeLevel,
}) => {
  // Navigation State
  const [selectedClass, setSelectedClass] = useState<string | null>(null);

  // Dynamic Academic Year based on July threshold
  const activeAcademicYear = useMemo(() => getCurrentAcademicYear(), []);

  // Academic Year State (Default: otomatis tahun ajaran aktif)
  const [selectedAcademicYear, setSelectedAcademicYear] = useState<string>(() =>
    getCurrentAcademicYear()
  );

  // Grade Summary State (for Grid Cards)
  const [gradeSummaries, setGradeSummaries] = useState<
    Array<{
      class_name: string;
      item_count: number;
      good_count: number;
      damaged_count: number;
      uninspected_count: number;
    }>
  >([]);
  const [isSummaryLoading, setIsSummaryLoading] = useState<boolean>(true);

  // Class Detail Items State
  const [items, setItems] = useState<ClassroomConditionItem[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState<string>("");

  // Modals
  const [isAddModalOpen, setIsAddModalOpen] = useState<boolean>(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState<boolean>(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState<boolean>(false);
  const [isPrintModalOpen, setIsPrintModalOpen] = useState<boolean>(false);

  // Selected item for Edit / Delete
  const [activeItem, setActiveItem] = useState<ClassroomConditionItem | null>(null);

  // Form State
  const [formData, setFormData] = useState<{
    item_name: string;
    quantity: string;
    condition: "baik" | "rusak" | "belum";
    notes: string;
    follow_up: string;
  }>({
    item_name: "",
    quantity: "",
    condition: "belum",
    notes: "",
    follow_up: "",
  });
  const [formError, setFormError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);

  // Toast
  const [toast, setToast] = useState<{ type: "success" | "error"; message: string } | null>(null);
  const showToast = (message: string, type: "success" | "error" = "success") => {
    setToast({ message, type });
    setTimeout(() => {
      setToast(null);
    }, 3500);
  };

  // Master Pejabat
  const { getOfficial } = useSchoolOfficials();
  const kepalaSekolah = getOfficial("kepala_sekolah");
  const wakasekSarana = getOfficial("wakasek_sarana");

  // Integrasi Data Wali Kelas dari Kurikulum
  const { getHomeroomForClass, teachers } = useSmartSchool();
  const [dbHomeroomMap, setDbHomeroomMap] = useState<
    Record<string, { name: string; nip?: string }>
  >({});

  useEffect(() => {
    let isMounted = true;
    async function loadTeachers() {
      try {
        const res = await fetch("/api/teachers");
        if (res.ok) {
          const json = await res.json();
          if (json.data && Array.isArray(json.data) && isMounted) {
            const map: Record<string, { name: string; nip?: string }> = {};
            json.data.forEach((t: any) => {
              if (t.homeroomClass) {
                map[String(t.homeroomClass).trim()] = {
                  name: t.fullName || t.name || t.nama || "",
                  nip: t.nip || t.nuptk || "",
                };
              }
            });
            setDbHomeroomMap(map);
          }
        }
      } catch (err) {
        console.error("Gagal memuat data wali kelas:", err);
      }
    }
    loadTeachers();
    return () => {
      isMounted = false;
    };
  }, []);

  // Wali Kelas terpilih sesuai kelas yang sedang aktif (misal: X-1 -> Yuke Anggia Murni, S.Pd.)
  const homeroomTeacher = useMemo(() => {
    if (!selectedClass) return null;
    const targetClass = selectedClass.trim();
    if (dbHomeroomMap[targetClass]?.name) {
      return dbHomeroomMap[targetClass];
    }
    const fromContext = getHomeroomForClass?.(targetClass);
    if (
      fromContext &&
      fromContext.teacherName &&
      fromContext.teacherName !== "Belum Ditugaskan"
    ) {
      return {
        name: fromContext.teacherName,
        nip: fromContext.nip !== "-" ? fromContext.nip : "",
      };
    }
    const teacherFromList = teachers?.find(
      (t) =>
        (Boolean(t.isHomeroomTeacher) || Boolean(t.homeroomClass)) &&
        t.homeroomClass?.trim() === targetClass
    );
    if (teacherFromList) {
      return {
        name: teacherFromList.fullName,
        nip: teacherFromList.nip || teacherFromList.nuptk || "",
      };
    }
    return null;
  }, [selectedClass, dbHomeroomMap, getHomeroomForClass, teachers]);

  // Fetch summary for the 10 classes in this grade level
  const fetchGradeSummaries = useCallback(async (year: string = selectedAcademicYear) => {
    try {
      setIsSummaryLoading(true);
      const res = await fetch(
        `/api/sarpras/classroom-conditions/summary?grade=${gradeLevel}&academic_year=${encodeURIComponent(year)}`,
        { cache: "no-store" }
      );
      const json = await res.json();
      if (json.success && json.data) {
        setGradeSummaries(json.data);
      }
    } catch (err) {
      console.error("fetchGradeSummaries error:", err);
    } finally {
      setIsSummaryLoading(false);
    }
  }, [gradeLevel, selectedAcademicYear]);

  // Fetch items for the selected classroom
  const fetchClassItems = useCallback(async (className: string, year: string = selectedAcademicYear) => {
    try {
      setIsLoading(true);
      setError(null);
      const res = await fetch(
        `/api/sarpras/classroom-conditions?class=${encodeURIComponent(className)}&academic_year=${encodeURIComponent(year)}`,
        { cache: "no-store" }
      );
      const json = await res.json();
      if (!res.ok || !json.success) {
        throw new Error(json.error || "Gagal memuat data kelas");
      }
      setItems(json.data || []);
    } catch (err: any) {
      console.error("fetchClassItems error:", err);
      setError(err.message || "Terjadi kesalahan saat memuat data");
    } finally {
      setIsLoading(false);
    }
  }, [selectedAcademicYear]);

  // Re-fetch summaries when gradeLevel or selectedAcademicYear changes
  useEffect(() => {
    fetchGradeSummaries(selectedAcademicYear);
  }, [fetchGradeSummaries, selectedAcademicYear]);

  // When selected class or selectedAcademicYear changes, fetch class items
  useEffect(() => {
    if (selectedClass) {
      fetchClassItems(selectedClass, selectedAcademicYear);
      setSearchTerm("");
    }
  }, [selectedClass, selectedAcademicYear, fetchClassItems]);

  // Filtered items in detail view
  const filteredItems = useMemo(() => {
    if (!searchTerm.trim()) return items;
    const term = searchTerm.toLowerCase();
    return items.filter(
      (i) =>
        i.item_name.toLowerCase().includes(term) ||
        (i.notes && i.notes.toLowerCase().includes(term)) ||
        (i.follow_up && i.follow_up.toLowerCase().includes(term))
    );
  }, [items, searchTerm]);

  // Stats for the active class
  const classStats = useMemo(() => {
    const total = items.length;
    const good = items.filter((i) => i.is_good === 1).length;
    const damaged = items.filter((i) => i.is_damaged === 1).length;
    const uninspected = items.filter((i) => i.is_good === 0 && i.is_damaged === 0).length;
    return { total, good, damaged, uninspected };
  }, [items]);

  // Toggle checkbox directly (Baik or Rusak)
  const handleToggleCondition = async (
    item: ClassroomConditionItem,
    type: "baik" | "rusak"
  ) => {
    let newIsGood = item.is_good;
    let newIsDamaged = item.is_damaged;

    if (type === "baik") {
      newIsGood = item.is_good === 1 ? 0 : 1;
      if (newIsGood === 1) newIsDamaged = 0; // mutually exclusive
    } else {
      newIsDamaged = item.is_damaged === 1 ? 0 : 1;
      if (newIsDamaged === 1) newIsGood = 0; // mutually exclusive
    }

    // Optimistic UI update
    setItems((prev) =>
      prev.map((i) =>
        i.id === item.id
          ? { ...i, is_good: newIsGood, is_damaged: newIsDamaged }
          : i
      )
    );

    try {
      const res = await fetch(`/api/sarpras/classroom-conditions/${item.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          is_good: newIsGood,
          is_damaged: newIsDamaged,
        }),
      });
      const json = await res.json();
      if (!res.ok || !json.success) {
        throw new Error(json.error || "Gagal menyimpan kondisi");
      }
      fetchGradeSummaries(); // refresh summary counts in background
    } catch (err: any) {
      showToast(err.message || "Gagal memperbarui status", "error");
      if (selectedClass) fetchClassItems(selectedClass); // revert on error
    }
  };

  // Open Add Modal
  const handleOpenAddModal = () => {
    setFormData({
      item_name: "",
      quantity: "",
      condition: "belum",
      notes: "",
      follow_up: "",
    });
    setFormError(null);
    setIsAddModalOpen(true);
  };

  // Submit Add
  const handleSubmitAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedClass) return;
    if (!formData.item_name.trim()) {
      setFormError("Nama item fasilitas wajib diisi");
      return;
    }

    try {
      setIsSubmitting(true);
      setFormError(null);
      const res = await fetch("/api/sarpras/classroom-conditions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          class_name: selectedClass,
          item_name: formData.item_name.trim(),
          quantity: formData.quantity ? parseInt(formData.quantity, 10) : null,
          is_good: formData.condition === "baik" ? 1 : 0,
          is_damaged: formData.condition === "rusak" ? 1 : 0,
          notes: formData.notes.trim() || null,
          follow_up: formData.follow_up.trim() || null,
          academic_year: selectedAcademicYear,
        }),
      });
      const json = await res.json();
      if (!res.ok || !json.success) {
        throw new Error(json.error || "Gagal menambahkan item");
      }
      showToast(`Item ${formData.item_name} berhasil ditambahkan`);
      setIsAddModalOpen(false);
      fetchClassItems(selectedClass, selectedAcademicYear);
      fetchGradeSummaries(selectedAcademicYear);
    } catch (err: any) {
      setFormError(err.message || "Terjadi kesalahan saat menyimpan");
    } finally {
      setIsSubmitting(false);
    }
  };

  // Open Edit Modal
  const handleOpenEditModal = (item: ClassroomConditionItem) => {
    setActiveItem(item);
    let cond: "baik" | "rusak" | "belum" = "belum";
    if (item.is_good === 1) cond = "baik";
    else if (item.is_damaged === 1) cond = "rusak";

    setFormData({
      item_name: item.item_name,
      quantity: item.quantity !== null && item.quantity !== undefined ? String(item.quantity) : "",
      condition: cond,
      notes: item.notes || "",
      follow_up: item.follow_up || "",
    });
    setFormError(null);
    setIsEditModalOpen(true);
  };

  // Submit Edit
  const handleSubmitEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!activeItem) return;
    if (!formData.item_name.trim()) {
      setFormError("Nama item fasilitas wajib diisi");
      return;
    }

    try {
      setIsSubmitting(true);
      setFormError(null);
      const res = await fetch(`/api/sarpras/classroom-conditions/${activeItem.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          item_name: formData.item_name.trim(),
          quantity: formData.quantity ? parseInt(formData.quantity, 10) : null,
          is_good: formData.condition === "baik" ? 1 : 0,
          is_damaged: formData.condition === "rusak" ? 1 : 0,
          notes: formData.notes.trim() || null,
          follow_up: formData.follow_up.trim() || null,
        }),
      });
      const json = await res.json();
      if (!res.ok || !json.success) {
        throw new Error(json.error || "Gagal memperbarui item");
      }
      showToast("Data item berhasil diperbarui");
      setIsEditModalOpen(false);
      setActiveItem(null);
      if (selectedClass) fetchClassItems(selectedClass, selectedAcademicYear);
      fetchGradeSummaries(selectedAcademicYear);
    } catch (err: any) {
      setFormError(err.message || "Terjadi kesalahan saat memperbarui");
    } finally {
      setIsSubmitting(false);
    }
  };

  // Open Delete Modal
  const handleOpenDeleteModal = (item: ClassroomConditionItem) => {
    setActiveItem(item);
    setIsDeleteModalOpen(true);
  };

  // Execute Delete
  const handleExecuteDelete = async () => {
    if (!activeItem) return;
    try {
      setIsSubmitting(true);
      const res = await fetch(`/api/sarpras/classroom-conditions/${activeItem.id}`, {
        method: "DELETE",
      });
      const json = await res.json();
      if (!res.ok || !json.success) {
        throw new Error(json.error || "Gagal menghapus item");
      }
      showToast("Item berhasil dihapus");
      setIsDeleteModalOpen(false);
      setActiveItem(null);
      if (selectedClass) fetchClassItems(selectedClass, selectedAcademicYear);
      fetchGradeSummaries(selectedAcademicYear);
    } catch (err: any) {
      showToast(err.message || "Terjadi kesalahan saat menghapus", "error");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Toast Feedback */}
      {toast && (
        <div
          className={`fixed bottom-5 right-5 z-50 print:hidden flex items-center gap-3 px-4 py-3 rounded-xl shadow-lg border text-sm font-medium transition-all transform animate-in slide-in-from-bottom-5 ${
            toast.type === "success"
              ? "bg-emerald-900/90 text-white border-emerald-700"
              : "bg-rose-900/90 text-white border-rose-700"
          }`}
        >
          {toast.type === "success" ? (
            <CheckCircle2 className="w-5 h-5 text-emerald-300" />
          ) : (
            <AlertTriangle className="w-5 h-5 text-rose-300" />
          )}
          <span>{toast.message}</span>
          <button onClick={() => setToast(null)} className="ml-2 text-white/70 hover:text-white">
            <X className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* ========================================================================= */}
      {/* VIEW 1: PILIHAN SUB-KELAS TINGKAT X / XI / XII (GRID CARDS SEPERTI GAMBAR 1) */}
      {/* ========================================================================= */}
      {!selectedClass && (
        <div className="space-y-6 print:hidden">
          {/* Header Banner Sub-Kelas Tingkat */}
          <div className="text-center max-w-2xl mx-auto pt-2 pb-1 space-y-2">
            <h1 className="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight">
              Pilihan Sub-Kelas Tingkat {gradeLevel}
            </h1>
            <p className="text-xs sm:text-sm text-slate-500 leading-relaxed">
              Pilih salah satu kelas di bawah ini untuk memeriksa, mencatat, atau memperbarui kondisi fasilitas dan sarana di dalam ruang kelas.
            </p>
            {/* Filter Tahun Ajaran pada View 1 */}
            <div className="pt-2 flex items-center justify-center gap-2">
              <span className="text-xs font-semibold text-slate-600 flex items-center gap-1.5">
                <Calendar className="w-3.5 h-3.5 text-blue-600" />
                Tahun Ajaran:
              </span>
              <select
                value={selectedAcademicYear}
                onChange={(e) => setSelectedAcademicYear(e.target.value)}
                className="bg-white border border-slate-300 rounded-xl px-3 py-1.5 text-xs font-bold text-slate-800 shadow-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 cursor-pointer"
              >
                {ACADEMIC_YEARS.map((y) => (
                  <option key={y} value={y}>
                    T.A. {y} {y === activeAcademicYear ? "(Aktif)" : ""}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Grid of 10 Class Cards (Image 1 reference) */}
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3.5 sm:gap-4 max-w-6xl mx-auto">
            {Array.from({ length: 10 }, (_, i) => {
              const className = `${gradeLevel}-${i + 1}`;
              const summary = gradeSummaries.find(
                (s) => s.class_name.toUpperCase() === className.toUpperCase()
              );
              const itemCount = summary ? summary.item_count : 21;
              const hasDamaged = summary && summary.damaged_count > 0;

              return (
                <div
                  key={className}
                  onClick={() => setSelectedClass(className)}
                  className="bg-white rounded-2xl border border-slate-200/90 p-5 sm:p-6 text-center shadow-xs hover:shadow-md hover:border-blue-400 hover:-translate-y-0.5 transition-all cursor-pointer group flex flex-col items-center justify-center space-y-2.5"
                >
                  {/* Soft Blue Icon Container */}
                  <div className="w-11 h-11 rounded-2xl bg-blue-50 border border-blue-100 flex items-center justify-center text-blue-600 group-hover:bg-blue-600 group-hover:text-white transition-all shadow-xs">
                    <Home className="w-5 h-5" />
                  </div>

                  {/* Class Title */}
                  <h3 className="text-base sm:text-lg font-bold text-slate-900 group-hover:text-blue-600 transition-colors">
                    Kelas {className}
                  </h3>

                  {/* Subtitle Item Count */}
                  <p className="text-xs text-slate-500 font-medium">
                    {itemCount} Item Dicatat
                  </p>

                  {/* Status Badge */}
                  <div className="pt-0.5">
                    {hasDamaged ? (
                      <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-amber-600 bg-amber-50 px-2.5 py-0.5 rounded-full border border-amber-200">
                        {summary.damaged_count} Perlu Perbaikan
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-600 bg-emerald-50 px-2.5 py-0.5 rounded-full border border-emerald-200">
                        Kondisi Terpantau
                      </span>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* VIEW 2: TABEL DETAIL KONDISI KELAS TERPILIH (SEPERTI GAMBAR 2) */}
      {/* ========================================================================= */}
      {selectedClass && (
        <div className="space-y-6 print:hidden">
          {/* Header Action Bar */}
          <div className="bg-white rounded-2xl border border-slate-200/80 p-5 sm:p-6 shadow-sm print:hidden">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div>
                <button
                  onClick={() => setSelectedClass(null)}
                  className="inline-flex items-center gap-1.5 text-xs font-semibold text-blue-600 hover:text-blue-700 mb-2 transition-colors cursor-pointer"
                >
                  <ArrowLeft className="w-3.5 h-3.5" />
                  <span>Kembali ke Pilihan Sub-Kelas Tingkat {gradeLevel}</span>
                </button>
                <div className="flex flex-wrap items-center gap-2">
                  <h1 className="text-2xl font-bold text-slate-900 tracking-tight">
                    Pemeriksaan Sarana Kelas {selectedClass}
                  </h1>
                  <span className="px-2.5 py-0.5 text-xs font-bold rounded-lg bg-blue-50 text-blue-700 border border-blue-200">
                    Tingkat {gradeLevel}
                  </span>
                  <span className="px-2.5 py-0.5 text-xs font-bold rounded-lg bg-emerald-50 text-emerald-700 border border-emerald-200">
                    T.A. {selectedAcademicYear}
                  </span>
                </div>
                <p className="text-xs text-slate-500 mt-1">
                  Catat kelengkapan dan kondisi fisik fasilitas, perabot, dan sarana ruang kelas SMA BPI 1 Bandung.
                </p>
              </div>

              <div className="flex flex-wrap items-center gap-2.5">
                {/* Dropdown Tahun Ajaran di Action Bar */}
                <div className="flex items-center gap-1.5 bg-slate-100 hover:bg-slate-200/80 border border-slate-200 rounded-xl px-3 py-1.5 transition-colors">
                  <Calendar className="w-3.5 h-3.5 text-blue-600" />
                  <span className="text-xs font-semibold text-slate-600">T.A:</span>
                  <select
                    value={selectedAcademicYear}
                    onChange={(e) => setSelectedAcademicYear(e.target.value)}
                    className="bg-transparent text-xs font-bold text-slate-800 border-none outline-none cursor-pointer focus:ring-0"
                    title="Pilih Tahun Ajaran"
                  >
                    {ACADEMIC_YEARS.map((y) => (
                      <option key={y} value={y}>
                        {y} {y === activeAcademicYear ? "(Aktif)" : ""}
                      </option>
                    ))}
                  </select>
                </div>

                <button
                  onClick={() => setIsPrintModalOpen(true)}
                  className="inline-flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-slate-700 bg-slate-100 hover:bg-slate-200 border border-slate-200 rounded-xl transition-colors cursor-pointer"
                  title="Cetak Lembar Kondisi Kelas"
                >
                  <Printer className="w-3.5 h-3.5 text-slate-600" />
                  <span>Cetak Rekap</span>
                </button>

                <button
                  onClick={handleOpenAddModal}
                  className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 active:bg-blue-800 rounded-xl shadow-sm transition-all cursor-pointer"
                >
                  <Plus className="w-3.5 h-3.5" />
                  <span>+ Tambah Item</span>
                </button>
              </div>
            </div>
          </div>

          {/* Quick Metrics */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3.5 print:hidden">
            <StatCard
              title="Total Item Fasilitas"
              value={isLoading ? "..." : `${classStats.total} Item`}
              icon={ClipboardCheck}
              description="Sarana terdaftar di kelas"
              variant="primary"
            />
            <StatCard
              title="Kondisi Baik"
              value={isLoading ? "..." : `${classStats.good} Item`}
              icon={CheckCircle2}
              description="Fasilitas berfungsi normal"
              variant="success"
            />
            <StatCard
              title="Kondisi Rusak"
              value={isLoading ? "..." : `${classStats.damaged} Item`}
              icon={AlertTriangle}
              description="Perlu perbaikan/tindak lanjut"
              variant="warning"
            />
            <StatCard
              title="Belum Diperiksa"
              value={isLoading ? "..." : `${classStats.uninspected} Item`}
              icon={Layers}
              description="Menunggu checklist petugas"
              variant="blue"
            />
          </div>

          {/* Table Container */}
          <div className="bg-white rounded-2xl border border-slate-200/80 shadow-sm overflow-hidden print:hidden">
            {/* Search filter */}
            <div className="p-4 border-b border-slate-100 bg-slate-50/50 flex flex-col sm:flex-row sm:items-center justify-between gap-3 print:hidden">
              <div className="flex flex-wrap items-center gap-2.5 flex-1">
                <div className="relative w-full sm:max-w-xs">
                  <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                  <input
                    type="text"
                    placeholder="Cari item fasilitas atau catatan..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-9 pr-8 py-2 bg-white border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder:text-slate-400"
                  />
                  {searchTerm && (
                    <button
                      onClick={() => setSearchTerm("")}
                      className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                    >
                      <X className="w-3.5 h-3.5" />
                    </button>
                  )}
                </div>

                {/* Dropdown Filter Tahun Ajaran */}
                <div className="flex items-center gap-1.5 bg-white border border-slate-200 rounded-xl px-3 py-1.5 shadow-xs">
                  <Calendar className="w-3.5 h-3.5 text-blue-600" />
                  <span className="text-xs text-slate-500 whitespace-nowrap">Tahun Ajaran:</span>
                  <select
                    value={selectedAcademicYear}
                    onChange={(e) => setSelectedAcademicYear(e.target.value)}
                    className="bg-transparent text-xs font-bold text-slate-800 border-none outline-none cursor-pointer focus:ring-0"
                  >
                    {ACADEMIC_YEARS.map((y) => (
                      <option key={y} value={y}>
                        {y} {y === activeAcademicYear ? "(Aktif)" : ""}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="text-xs text-slate-500 whitespace-nowrap">
                Menampilkan <span className="font-semibold text-slate-900">{filteredItems.length}</span> item di Kelas {selectedClass} • T.A. {selectedAcademicYear}
              </div>
            </div>

            {/* Table (Matching image 2 structure: media_1791284443265.png) */}
            {isLoading ? (
              <div className="py-20 flex flex-col items-center justify-center text-slate-400">
                <RefreshCw className="w-8 h-8 animate-spin text-blue-600 mb-3" />
                <p className="text-sm font-medium">Memuat data kondisi kelas...</p>
              </div>
            ) : error ? (
              <div className="py-16 text-center">
                <AlertTriangle className="w-10 h-10 text-rose-500 mx-auto mb-3" />
                <p className="text-sm font-semibold text-slate-800">{error}</p>
                <button
                  onClick={() => fetchClassItems(selectedClass, selectedAcademicYear)}
                  className="mt-3 px-4 py-2 bg-blue-600 text-white text-xs font-semibold rounded-lg hover:bg-blue-700"
                >
                  Coba Lagi
                </button>
              </div>
            ) : filteredItems.length === 0 ? (
              <div className="py-16 text-center">
                <ClipboardCheck className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                <p className="text-base font-semibold text-slate-700">Item tidak ditemukan</p>
                <p className="text-xs text-slate-500 mt-1 max-w-sm mx-auto">
                  Coba sesuaikan kata kunci pencarian atau klik Tambah Item untuk menambah item fasilitas baru.
                </p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    {/* Header Row 1 */}
                    <tr className="bg-slate-50 border-b border-slate-200 text-slate-700 text-xs font-bold uppercase tracking-wider">
                      <th rowSpan={2} className="py-3 px-3 text-center border-r border-slate-200 w-12">
                        NO
                      </th>
                      <th rowSpan={2} className="py-3 px-4 border-r border-slate-200 min-w-[200px]">
                        ITEM
                      </th>
                      <th colSpan={5} className="py-2.5 px-4 text-center border-r border-slate-200 bg-slate-100/70">
                        KONDISI KELAS
                      </th>
                      <th rowSpan={2} className="py-3 px-3 text-center w-24">
                        AKSI
                      </th>
                    </tr>
                    {/* Header Row 2 (Sub-columns under KONDISI KELAS) */}
                    <tr className="bg-slate-50/80 border-b border-slate-200 text-slate-600 text-[11px] font-bold uppercase tracking-wider">
                      <th className="py-2 px-3 text-center border-r border-slate-200 w-24">JUMLAH</th>
                      <th className="py-2 px-3 text-center border-r border-slate-200 w-20">BAIK</th>
                      <th className="py-2 px-3 text-center border-r border-slate-200 w-20">RUSAK</th>
                      <th className="py-2 px-3.5 border-r border-slate-200 min-w-[180px]">CATATAN</th>
                      <th className="py-2 px-3.5 border-r border-slate-200 min-w-[180px]">TINDAK LANJUT</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100 text-xs text-slate-700">
                    {filteredItems.map((item, index) => (
                      <tr key={item.id} className="hover:bg-slate-50/80 transition-colors">
                        <td className="py-3 px-3 text-center font-medium text-slate-500 border-r border-slate-100">
                          {index + 1}
                        </td>
                        <td className="py-3 px-4 font-semibold text-slate-900 border-r border-slate-100">
                          {item.item_name}
                        </td>
                        <td className="py-3 px-3 text-center font-bold text-slate-800 border-r border-slate-100">
                          {item.quantity !== null && item.quantity !== undefined
                            ? item.quantity
                            : "-"}
                        </td>
                        {/* Checkbox Baik */}
                        <td className="py-3 px-3 text-center border-r border-slate-100">
                          <button
                            type="button"
                            onClick={() => handleToggleCondition(item, "baik")}
                            className="inline-flex items-center justify-center p-1 rounded-md hover:bg-emerald-50 transition-colors cursor-pointer"
                            title={item.is_good === 1 ? "Kondisi Baik (Aktif)" : "Centang Kondisi Baik"}
                          >
                            {item.is_good === 1 ? (
                              <CheckSquare className="w-5 h-5 text-emerald-600 fill-emerald-50" />
                            ) : (
                              <Square className="w-5 h-5 text-slate-300 hover:text-slate-400" />
                            )}
                          </button>
                        </td>
                        {/* Checkbox Rusak */}
                        <td className="py-3 px-3 text-center border-r border-slate-100">
                          <button
                            type="button"
                            onClick={() => handleToggleCondition(item, "rusak")}
                            className="inline-flex items-center justify-center p-1 rounded-md hover:bg-rose-50 transition-colors cursor-pointer"
                            title={item.is_damaged === 1 ? "Kondisi Rusak (Aktif)" : "Centang Kondisi Rusak"}
                          >
                            {item.is_damaged === 1 ? (
                              <CheckSquare className="w-5 h-5 text-rose-600 fill-rose-50" />
                            ) : (
                              <Square className="w-5 h-5 text-slate-300 hover:text-slate-400" />
                            )}
                          </button>
                        </td>
                        <td className="py-3 px-3.5 border-r border-slate-100 text-slate-600">
                          {item.notes || "-"}
                        </td>
                        <td className="py-3 px-3.5 border-r border-slate-100 text-slate-600">
                          {item.follow_up ? (
                            <span className="text-amber-700 font-medium bg-amber-50 px-2 py-0.5 rounded border border-amber-200/70 inline-block text-[11px]">
                              {item.follow_up}
                            </span>
                          ) : (
                            "-"
                          )}
                        </td>
                        <td className="py-3 px-3 text-center">
                          <div className="flex items-center justify-center gap-1.5">
                            <button
                              onClick={() => handleOpenEditModal(item)}
                              className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors cursor-pointer"
                              title="Edit Item"
                            >
                              <Pencil className="w-3.5 h-3.5" />
                            </button>
                            <button
                              onClick={() => handleOpenDeleteModal(item)}
                              className="p-1.5 text-rose-600 hover:bg-rose-50 rounded-lg transition-colors cursor-pointer"
                              title="Hapus Item"
                            >
                              <Trash2 className="w-3.5 h-3.5" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ==================================================== */}
      {/* MODAL: TAMBAH ITEM KONDISI KELAS */}
      {/* ==================================================== */}
      <Modal
        isOpen={isAddModalOpen}
        onClose={() => setIsAddModalOpen(false)}
        title={`Tambah Item Fasilitas Kelas ${selectedClass}`}
        description="Tambahkan sarana fisik tambahan untuk diperiksa"
        maxWidth="max-w-md"
      >
        <form onSubmit={handleSubmitAdd} className="space-y-4 pt-1">
          {formError && (
            <div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 text-xs flex items-center gap-2">
              <AlertTriangle className="w-4 h-4 shrink-0" />
              <span>{formError}</span>
            </div>
          )}

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Nama Item Fasilitas <span className="text-rose-500">*</span>
            </label>
            <input
              type="text"
              placeholder="Contoh: Kipas Angin / Dispenser / Terminal Listrik"
              value={formData.item_name}
              onChange={(e) => setFormData({ ...formData, item_name: e.target.value })}
              className="w-full px-3 py-2 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
              required
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-semibold text-slate-700 mb-1">
                Jumlah / Qty
              </label>
              <input
                type="number"
                min="0"
                placeholder="Kosongkan jika belum terdata"
                value={formData.quantity}
                onChange={(e) => setFormData({ ...formData, quantity: e.target.value })}
                className="w-full px-3 py-2 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700 mb-1">
                Status Kondisi
              </label>
              <select
                value={formData.condition}
                onChange={(e) => setFormData({ ...formData, condition: e.target.value as any })}
                className="w-full px-3 py-2 bg-white border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
              >
                <option value="belum">Belum Dicek</option>
                <option value="baik">Kondisi Baik</option>
                <option value="rusak">Kondisi Rusak</option>
              </select>
            </div>
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">Catatan</label>
            <textarea
              rows={2}
              placeholder="Catatan kondisi spesifik..."
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              className="w-full px-3 py-2 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">Tindak Lanjut</label>
            <input
              type="text"
              placeholder="Contoh: Penggantian bohlam / Perbaikan teknisi sarpras"
              value={formData.follow_up}
              onChange={(e) => setFormData({ ...formData, follow_up: e.target.value })}
              className="w-full px-3 py-2 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
            />
          </div>

          <div className="flex items-center justify-end gap-2.5 pt-3 border-t border-slate-100">
            <button
              type="button"
              onClick={() => setIsAddModalOpen(false)}
              className="px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-100 rounded-xl transition-colors cursor-pointer"
            >
              Batal
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-5 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 active:bg-blue-800 rounded-xl shadow-sm transition-all disabled:opacity-50 flex items-center gap-2 cursor-pointer"
            >
              {isSubmitting && <RefreshCw className="w-3.5 h-3.5 animate-spin" />}
              <span>Simpan Item</span>
            </button>
          </div>
        </form>
      </Modal>

      {/* ==================================================== */}
      {/* MODAL: EDIT ITEM KONDISI KELAS */}
      {/* ==================================================== */}
      <Modal
        isOpen={isEditModalOpen}
        onClose={() => setIsEditModalOpen(false)}
        title="Edit Item Kondisi Kelas"
        description="Perbarui jumlah dan status pemeriksaan fasilitas"
        maxWidth="max-w-md"
      >
        <form onSubmit={handleSubmitEdit} className="space-y-4 pt-1">
          {formError && (
            <div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 text-xs flex items-center gap-2">
              <AlertTriangle className="w-4 h-4 shrink-0" />
              <span>{formError}</span>
            </div>
          )}

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Nama Item Fasilitas <span className="text-rose-500">*</span>
            </label>
            <input
              type="text"
              value={formData.item_name}
              onChange={(e) => setFormData({ ...formData, item_name: e.target.value })}
              className="w-full px-3 py-2 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
              required
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-semibold text-slate-700 mb-1">
                Jumlah / Qty
              </label>
              <input
                type="number"
                min="0"
                placeholder="Kosong"
                value={formData.quantity}
                onChange={(e) => setFormData({ ...formData, quantity: e.target.value })}
                className="w-full px-3 py-2 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700 mb-1">
                Kondisi Fasilitas
              </label>
              <select
                value={formData.condition}
                onChange={(e) => setFormData({ ...formData, condition: e.target.value as any })}
                className="w-full px-3 py-2 bg-white border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
              >
                <option value="belum">Belum Dicek</option>
                <option value="baik">Kondisi Baik</option>
                <option value="rusak">Kondisi Rusak</option>
              </select>
            </div>
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">Catatan</label>
            <textarea
              rows={2}
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              className="w-full px-3 py-2 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">Tindak Lanjut</label>
            <input
              type="text"
              value={formData.follow_up}
              onChange={(e) => setFormData({ ...formData, follow_up: e.target.value })}
              className="w-full px-3 py-2 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
            />
          </div>

          <div className="flex items-center justify-end gap-2.5 pt-3 border-t border-slate-100">
            <button
              type="button"
              onClick={() => setIsEditModalOpen(false)}
              className="px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-100 rounded-xl transition-colors cursor-pointer"
            >
              Batal
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-5 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 active:bg-blue-800 rounded-xl shadow-sm transition-all disabled:opacity-50 flex items-center gap-2 cursor-pointer"
            >
              {isSubmitting && <RefreshCw className="w-3.5 h-3.5 animate-spin" />}
              <span>Simpan Perubahan</span>
            </button>
          </div>
        </form>
      </Modal>

      {/* ==================================================== */}
      {/* MODAL: HAPUS ITEM */}
      {/* ==================================================== */}
      <Modal
        isOpen={isDeleteModalOpen}
        onClose={() => setIsDeleteModalOpen(false)}
        title="Hapus Item Fasilitas"
        description="Konfirmasi penghapusan item dari daftar kelas"
        maxWidth="max-w-md"
      >
        <div className="space-y-4 pt-1">
          <p className="text-xs text-slate-600 leading-relaxed">
            Apakah Anda yakin ingin menghapus item fasilitas{" "}
            <span className="font-bold text-slate-900">{activeItem?.item_name}</span> dari Kelas {selectedClass}?
          </p>

          <div className="flex items-center justify-end gap-2.5 pt-3 border-t border-slate-100">
            <button
              type="button"
              onClick={() => setIsDeleteModalOpen(false)}
              className="px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-100 rounded-xl transition-colors cursor-pointer"
            >
              Batal
            </button>
            <button
              type="button"
              onClick={handleExecuteDelete}
              disabled={isSubmitting}
              className="px-5 py-2 text-xs font-semibold text-white bg-rose-600 hover:bg-rose-700 active:bg-rose-800 rounded-xl shadow-sm transition-all disabled:opacity-50 flex items-center gap-2 cursor-pointer"
            >
              {isSubmitting && <RefreshCw className="w-3.5 h-3.5 animate-spin" />}
              <span>Hapus Sekarang</span>
            </button>
          </div>
        </div>
      </Modal>

      {/* ==================================================== */}
      {/* MODAL: PRATINJAU CETAK DOKUMEN REKAP KONDISI KELAS */}
      {/* ==================================================== */}
      <Modal
        isOpen={isPrintModalOpen}
        onClose={() => setIsPrintModalOpen(false)}
        title={`Pratinjau Cetak Kondisi Sarana Kelas ${selectedClass || ""}`}
        description="Format lembar pemeriksaan resmi fasilitas ruang kelas SMA BPI 1 Bandung"
        maxWidth="max-w-5xl"
        hideOnPrint={false}
        footer={
          <div className="flex items-center justify-between w-full">
            <div className="text-xs text-slate-500">
              * Dokumen dicetak dengan Kop Surat Resmi Yayasan BPI - SMA BPI 1 Bandung
            </div>
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => setIsPrintModalOpen(false)}
                className="px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-100 rounded-xl transition-colors cursor-pointer"
              >
                Tutup
              </button>
              <button
                type="button"
                onClick={() => {
                  if (typeof document !== "undefined") {
                    document.body.style.overflow = "visible";
                  }
                  window.print();
                }}
                className="inline-flex items-center gap-2 px-4 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 active:bg-blue-800 rounded-xl shadow-sm transition-all cursor-pointer"
              >
                <Printer className="w-3.5 h-3.5" />
                <span>Cetak Sekarang (Print / PDF)</span>
              </button>
            </div>
          </div>
        }
      >
        <div id="print-classroom-document" className="printable-document printable-area bg-white p-2 sm:p-4 text-slate-900 font-sans print-portrait">
          {/* KOP SURAT RESMI SMA BPI 1 BANDUNG (UKURAN SIMETRIS & SATU GARIS PEMISAH) */}
          <div className="w-full mb-2">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src="/images/kop-surat-bpi.png"
              alt="Kop Surat Resmi Yayasan BPI - SMA BPI 1 Bandung"
              className="w-full h-auto block"
            />
          </div>

          {/* JUDUL DOKUMEN REKAPITULASI (TANPA GARIS BAWAH TAMBAHAN) */}
          <div className="text-center space-y-0.5 mb-2.5 pt-0.5">
            <h2 className="text-sm font-bold uppercase tracking-wider text-slate-900">
              LEMBAR PEMERIKSAAN ITEM & KONDISI SARANA KELAS {selectedClass}
            </h2>
            <p className="text-[11px] font-semibold text-slate-700">
              SMA BPI 1 BANDUNG • TAHUN AJARAN {selectedAcademicYear}
            </p>
            <p className="text-[10px] text-slate-500">
              Dicetak pada: {new Date().toLocaleDateString("id-ID", { dateStyle: "full" })}
            </p>
          </div>

          {/* Ringkasan Status */}
          <div className="mb-2.5 grid grid-cols-4 gap-2 text-[10px] bg-slate-50 p-2 rounded-lg border border-slate-200">
            <div>
              <span className="text-slate-500 block">Ruang & T.A.:</span>
              <span className="font-bold text-slate-800">Kelas {selectedClass} ({selectedAcademicYear})</span>
            </div>
            <div>
              <span className="text-slate-500 block">Total Item Fasilitas:</span>
              <span className="font-bold text-slate-800">{classStats.total} Item</span>
            </div>
            <div>
              <span className="text-slate-500 block">Kondisi Baik:</span>
              <span className="font-bold text-emerald-700">{classStats.good} Item</span>
            </div>
            <div>
              <span className="text-slate-500 block">Kondisi Rusak / Perbaikan:</span>
              <span className="font-bold text-rose-700">{classStats.damaged} Item</span>
            </div>
          </div>

          {/* Tabel Pemeriksaan 2-Tier Header */}
          <div className="w-full overflow-hidden print:overflow-visible">
            <table className="w-full text-left text-[10px] border-collapse border border-slate-300 table-fixed">
              <thead>
                <tr className="bg-slate-100 text-slate-900 font-bold uppercase text-[9.5px] tracking-wider border-b border-slate-300">
                  <th rowSpan={2} className="py-1 px-1 text-center w-[5%] border border-slate-300">
                    NO
                  </th>
                  <th rowSpan={2} className="py-1 px-2 border border-slate-300 w-[27%]">
                    ITEM
                  </th>
                  <th colSpan={5} className="py-0.5 px-1 text-center border border-slate-300 bg-slate-200/60 w-[68%]">
                    KONDISI KELAS
                  </th>
                </tr>
                <tr className="bg-slate-100 text-slate-900 font-bold uppercase text-[8.5px] border-b border-slate-300">
                  <th className="py-1 px-1 text-center border border-slate-300 w-[9%]">JUMLAH</th>
                  <th className="py-1 px-1 text-center border border-slate-300 w-[7%]">BAIK</th>
                  <th className="py-1 px-1 text-center border border-slate-300 w-[7%]">RUSAK</th>
                  <th className="py-1 px-1.5 border border-slate-300 w-[22%]">CATATAN</th>
                  <th className="py-1 px-1.5 border border-slate-300 w-[23%]">TINDAK LANJUT</th>
                </tr>
              </thead>
              <tbody>
                {items.map((item, index) => (
                  <tr key={item.id} className="border-b border-slate-200">
                    <td className="py-0.5 px-1 text-center border border-slate-300 text-[9.5px]">{index + 1}</td>
                    <td className="py-0.5 px-2 font-semibold border border-slate-300 truncate text-[9.5px]">{item.item_name}</td>
                    <td className="py-0.5 px-1 text-center font-bold border border-slate-300 text-[9.5px]">
                      {item.quantity !== null && item.quantity !== undefined ? item.quantity : "-"}
                    </td>
                    <td className="py-0.5 px-1 text-center font-bold border border-slate-300 text-[9.5px]">
                      {item.is_good === 1 ? "✓" : "-"}
                    </td>
                    <td className="py-0.5 px-1 text-center font-bold text-rose-700 border border-slate-300 text-[9.5px]">
                      {item.is_damaged === 1 ? "✓" : "-"}
                    </td>
                    <td className="py-0.5 px-1.5 border border-slate-300 text-[9px] leading-tight break-words">{item.notes || "-"}</td>
                    <td className="py-0.5 px-1.5 border border-slate-300 text-[9px] leading-tight break-words">{item.follow_up || "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Official Signatures: Kiri Kepala Sekolah (Tatang, M.Pd), Kanan Wali Kelas */}
          <div className="mt-4 pt-2 grid grid-cols-2 gap-6 text-center text-xs signature-block signature-section">
            <div className="flex flex-col items-center">
              <p className="text-slate-600 mb-0.5 text-[11px]">Mengetahui,</p>
              <p className="font-bold text-slate-900 text-xs">
                {kepalaSekolah.title || "Kepala SMA BPI 1 Bandung"}
              </p>
              <div
                style={{ height: "55px", minHeight: "55px" }}
                className="w-full flex items-center justify-center my-1"
              >
                {kepalaSekolah.signature_image ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={kepalaSekolah.signature_image}
                    alt="Tanda Tangan Kepala Sekolah"
                    className="h-12 max-w-[120px] object-contain mx-auto"
                  />
                ) : (
                  <div style={{ height: "55px" }} />
                )}
              </div>
              <p className="font-bold text-slate-900 underline text-xs">
                {kepalaSekolah.name && kepalaSekolah.name !== "-"
                  ? kepalaSekolah.name
                  : "Tatang, M.Pd."}
              </p>
              <p className="text-[10px] text-slate-500 font-mono mt-0.5">
                {kepalaSekolah.nip && kepalaSekolah.nip !== "-"
                  ? kepalaSekolah.nip.startsWith("NIP")
                    ? kepalaSekolah.nip
                    : `NIP. ${kepalaSekolah.nip}`
                  : "NIPY. 10079"}
              </p>
            </div>
            <div className="flex flex-col items-center">
              <p className="text-slate-600 mb-0.5 text-[11px]">
                Bandung,{" "}
                {new Date().toLocaleDateString("id-ID", {
                  day: "numeric",
                  month: "long",
                  year: "numeric",
                })}
              </p>
              <p className="font-bold text-slate-900 text-xs">
                Wali Kelas {selectedClass}
              </p>
              <div
                style={{ height: "55px", minHeight: "55px" }}
                className="w-full flex items-center justify-center my-1"
              >
                {/* Ruang tanda tangan resmi wali kelas */}
                <div style={{ height: "55px" }} />
              </div>
              <p className="font-bold text-slate-900 underline text-xs">
                {homeroomTeacher?.name || `Wali Kelas ${selectedClass}`}
              </p>
              <p className="text-[10px] text-slate-500 font-mono mt-0.5">
                {homeroomTeacher?.nip &&
                homeroomTeacher.nip.trim() !== "" &&
                homeroomTeacher.nip !== "-"
                  ? homeroomTeacher.nip.startsWith("NIP") ||
                    homeroomTeacher.nip.startsWith("NUPTK")
                    ? homeroomTeacher.nip
                    : `NIP. ${homeroomTeacher.nip}`
                  : "NIPY. -"}
              </p>
            </div>
          </div>
        </div>
      </Modal>

    </div>
  );
};

export default ClassroomConditionView;
