"use client";

import React, { useState, useEffect, useMemo, useCallback } from "react";
import {
  Layers,
  Search,
  Plus,
  Pencil,
  Trash2,
  Printer,
  X,
  RefreshCw,
  CheckCircle2,
  AlertTriangle,
  ClipboardCheck,
  Calendar,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { Modal } from "@/components/ui/Modal";
import { StatCard } from "@/components/ui/StatCard";
import { useSchoolOfficials } from "@/hooks/useSchoolOfficials";
import { getCurrentAcademicYear, getAcademicYearOptions } from "@/lib/academicYear";

export const ACADEMIC_YEARS = getAcademicYearOptions();

export interface CorridorConditionItem {
  id: number;
  floor: number;
  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 CorridorConditionViewProps {
  currentFloor: 1 | 2 | 3;
}

export const CorridorConditionView: React.FC<CorridorConditionViewProps> = ({
  currentFloor,
}) => {
  const router = useRouter();

  // Active Floor state
  const [activeFloor, setActiveFloor] = useState<1 | 2 | 3>(currentFloor);

  useEffect(() => {
    setActiveFloor(currentFloor);
  }, [currentFloor]);

  // Academic Year State (Dynamic based on July threshold)
  const activeAcademicYear = useMemo(() => getCurrentAcademicYear(), []);
  const [selectedAcademicYear, setSelectedAcademicYear] = useState<string>(() =>
    getCurrentAcademicYear()
  );

  // Items State
  const [items, setItems] = useState<CorridorConditionItem[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  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);

  // Active Item for Edit / Delete
  const [activeItem, setActiveItem] = useState<CorridorConditionItem | 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 Sekolah (Kepala Sekolah & Wakasek Sarana)
  const { getOfficial } = useSchoolOfficials();
  const kepalaSekolah = getOfficial("kepala_sekolah");
  const wakasekSarana = getOfficial("wakasek_sarana");

  // Fetch Items
  const fetchCorridorItems = useCallback(
    async (floor: number = activeFloor, year: string = selectedAcademicYear) => {
      try {
        setIsLoading(true);
        setError(null);
        const res = await fetch(
          `/api/sarpras/corridor-conditions?floor=${floor}&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 kondisi koridor");
        }
        setItems(json.data || []);
      } catch (err: any) {
        console.error("fetchCorridorItems error:", err);
        setError(err.message || "Terjadi kesalahan saat memuat data");
      } finally {
        setIsLoading(false);
      }
    },
    [activeFloor, selectedAcademicYear]
  );

  useEffect(() => {
    fetchCorridorItems(activeFloor, selectedAcademicYear);
  }, [activeFloor, selectedAcademicYear, fetchCorridorItems]);

  // Handle Floor Switch Tab
  const handleFloorChange = (floor: 1 | 2 | 3) => {
    setActiveFloor(floor);
    router.push(`/sarpras/kondisi-koridor/lantai-${floor}`);
  };

  // Filtered Items
  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
  const corridorStats = 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 (Baik or Rusak)
  const handleToggleCondition = async (
    item: CorridorConditionItem,
    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/corridor-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");
      }
    } catch (err: any) {
      showToast(err.message || "Gagal memperbarui status", "error");
      fetchCorridorItems(activeFloor, selectedAcademicYear); // 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 (!formData.item_name.trim()) {
      setFormError("Nama item fasilitas koridor wajib diisi");
      return;
    }

    try {
      setIsSubmitting(true);
      setFormError(null);
      const res = await fetch("/api/sarpras/corridor-conditions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          floor: activeFloor,
          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);
      fetchCorridorItems(activeFloor, selectedAcademicYear);
    } catch (err: any) {
      setFormError(err.message || "Terjadi kesalahan saat menyimpan");
    } finally {
      setIsSubmitting(false);
    }
  };

  // Open Edit Modal
  const handleOpenEditModal = (item: CorridorConditionItem) => {
    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 koridor wajib diisi");
      return;
    }

    try {
      setIsSubmitting(true);
      setFormError(null);
      const res = await fetch(`/api/sarpras/corridor-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);
      fetchCorridorItems(activeFloor, selectedAcademicYear);
    } catch (err: any) {
      setFormError(err.message || "Terjadi kesalahan saat memperbarui");
    } finally {
      setIsSubmitting(false);
    }
  };

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

  // Execute Delete
  const handleExecuteDelete = async () => {
    if (!activeItem) return;
    try {
      setIsSubmitting(true);
      const res = await fetch(`/api/sarpras/corridor-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);
      fetchCorridorItems(activeFloor, 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 flex items-center gap-2.5 px-4 py-3 rounded-xl shadow-lg border text-sm font-medium transition-all ${
            toast.type === "success"
              ? "bg-slate-900 text-white border-slate-800"
              : "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>
      )}

      {/* Floor Selection Tabs */}
      <div className="bg-white rounded-2xl border border-slate-200/80 p-3 shadow-xs print:hidden">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div className="flex items-center gap-1.5 p-1 bg-slate-100 rounded-xl">
            {([1, 2, 3] as const).map((floor) => (
              <button
                key={floor}
                onClick={() => handleFloorChange(floor)}
                className={`px-4 py-2 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                  activeFloor === floor
                    ? "bg-white text-blue-600 shadow-xs"
                    : "text-slate-600 hover:text-slate-900"
                }`}
              >
                Koridor Lantai {floor}
              </button>
            ))}
          </div>

          <div className="text-xs text-slate-500 font-medium px-2">
            Pemeriksaan sarana koridor lingkungan SMA BPI 1 Bandung
          </div>
        </div>
      </div>

      {/* 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>
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="text-2xl font-bold text-slate-900 tracking-tight">
                Item & Kondisi Koridor Lantai {activeFloor}
              </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">
                Lantai {activeFloor}
              </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 kelayakan fasilitas, pintu, lantai koridor, lampu penerangan, tempat sampah terpilah, serta APAR di Koridor Lantai {activeFloor}.
            </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 Koridor"
            >
              <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 Koridor</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 Koridor"
          value={isLoading ? "..." : `${corridorStats.total} Item`}
          icon={ClipboardCheck}
          description="Fasilitas terdaftar di koridor"
          variant="primary"
        />
        <StatCard
          title="Kondisi Baik"
          value={isLoading ? "..." : `${corridorStats.good} Item`}
          icon={CheckCircle2}
          description="Kondisi berfungsi normal"
          variant="success"
        />
        <StatCard
          title="Kondisi Rusak"
          value={isLoading ? "..." : `${corridorStats.damaged} Item`}
          icon={AlertTriangle}
          description="Perlu perbaikan/tindak lanjut"
          variant="warning"
        />
        <StatCard
          title="Belum Diperiksa"
          value={isLoading ? "..." : `${corridorStats.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 Koridor Lantai {activeFloor} • T.A. {selectedAcademicYear}
          </div>
        </div>

        {/* Table */}
        {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 koridor...</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={() => fetchCorridorItems(activeFloor, 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 Koridor untuk menambah fasilitas baru.
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <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 px-3 text-center border-r border-slate-200 bg-slate-100/70">
                    KONDISI KORIDOR
                  </th>
                  <th rowSpan={2} className="py-3 px-3 text-center w-28">
                    AKSI
                  </th>
                </tr>
                <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-2.5 text-center border-r border-slate-200 w-24">JUMLAH</th>
                  <th className="py-2 px-2 text-center border-r border-slate-200 w-20">BAIK</th>
                  <th className="py-2 px-2 text-center border-r border-slate-200 w-20">RUSAK</th>
                  <th className="py-2 px-3 border-r border-slate-200 min-w-[180px]">CATATAN</th>
                  <th className="py-2 px-3 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 group">
                    {/* 1. NO */}
                    <td className="py-3.5 px-3 text-center font-medium text-slate-400 border-r border-slate-100">
                      {index + 1}
                    </td>

                    {/* 2. ITEM */}
                    <td className="py-3.5 px-4 font-semibold text-slate-900 border-r border-slate-100">
                      <div className="flex items-center gap-2">
                        <span className="w-1.5 h-1.5 rounded-full bg-blue-500 shrink-0" />
                        <span>{item.item_name}</span>
                      </div>
                    </td>

                    {/* 3. JUMLAH */}
                    <td className="py-3.5 px-2.5 text-center font-bold text-slate-800 border-r border-slate-100">
                      {item.quantity !== null && item.quantity !== undefined ? (
                        <span className="px-2 py-0.5 rounded bg-slate-100 border border-slate-200 font-mono text-xs">
                          {item.quantity}
                        </span>
                      ) : (
                        <span className="text-slate-300">-</span>
                      )}
                    </td>

                    {/* 4. BAIK (Checkbox) */}
                    <td className="py-3.5 px-2 text-center border-r border-slate-100">
                      <label className="inline-flex items-center justify-center cursor-pointer p-1">
                        <input
                          type="checkbox"
                          checked={item.is_good === 1}
                          onChange={() => handleToggleCondition(item, "baik")}
                          className="w-4 h-4 text-emerald-600 rounded border-slate-300 focus:ring-emerald-500 focus:ring-2 cursor-pointer transition-all"
                        />
                      </label>
                    </td>

                    {/* 5. RUSAK (Checkbox) */}
                    <td className="py-3.5 px-2 text-center border-r border-slate-100">
                      <label className="inline-flex items-center justify-center cursor-pointer p-1">
                        <input
                          type="checkbox"
                          checked={item.is_damaged === 1}
                          onChange={() => handleToggleCondition(item, "rusak")}
                          className="w-4 h-4 text-rose-600 rounded border-slate-300 focus:ring-rose-500 focus:ring-2 cursor-pointer transition-all"
                        />
                      </label>
                    </td>

                    {/* 6. CATATAN */}
                    <td className="py-3.5 px-3 text-slate-600 border-r border-slate-100 max-w-xs truncate">
                      {item.notes ? (
                        <span title={item.notes}>{item.notes}</span>
                      ) : (
                        <span className="text-slate-300 italic text-[11px]">-</span>
                      )}
                    </td>

                    {/* 7. TINDAK LANJUT */}
                    <td className="py-3.5 px-3 text-slate-600 border-r border-slate-100 max-w-xs truncate">
                      {item.follow_up ? (
                        <span className="text-amber-800 font-medium" title={item.follow_up}>
                          {item.follow_up}
                        </span>
                      ) : (
                        <span className="text-slate-300 italic text-[11px]">-</span>
                      )}
                    </td>

                    {/* 8. AKSI */}
                    <td className="py-3.5 px-3 text-center">
                      <div className="flex items-center justify-center gap-1.5">
                        <button
                          onClick={() => handleOpenEditModal(item)}
                          className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold text-blue-700 bg-blue-50 hover:bg-blue-100 border border-blue-200/80 transition-colors cursor-pointer"
                          title="Edit Item Koridor"
                        >
                          <Pencil className="w-3 h-3" />
                          <span>Edit</span>
                        </button>
                        <button
                          onClick={() => handleOpenDeleteModal(item)}
                          className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold text-rose-700 bg-rose-50 hover:bg-rose-100 border border-rose-200/80 transition-colors cursor-pointer"
                          title="Hapus Item Koridor"
                        >
                          <Trash2 className="w-3 h-3" />
                          <span>Hapus</span>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Footer info */}
        <div className="p-4 border-t border-slate-100 bg-slate-50/50 flex flex-col sm:flex-row items-center justify-between gap-2 text-xs text-slate-500 print:hidden">
          <div>
            Total <span className="font-semibold text-slate-900">{filteredItems.length}</span> fasilitas koridor terdaftar pada Lantai {activeFloor}
          </div>
          <div>Data terhubung secara real-time ke Dashboard Sarana & Prasarana</div>
        </div>
      </div>

      {/* ==================================================== */}
      {/* MODAL: TAMBAH ITEM KORIDOR BARU */}
      {/* ==================================================== */}
      <Modal
        isOpen={isAddModalOpen}
        onClose={() => setIsAddModalOpen(false)}
        title={`Tambah Item Fasilitas Koridor Lantai ${activeFloor}`}
        description="Tambahkan fasilitas atau perabot baru pada koridor lantai terkait."
        maxWidth="max-w-lg"
      >
        <form onSubmit={handleSubmitAdd} className="space-y-4">
          {formError && (
            <div className="p-3 bg-rose-50 border border-rose-200 rounded-xl text-rose-700 text-xs font-medium flex items-center gap-2">
              <AlertTriangle className="w-4 h-4 shrink-0 text-rose-500" />
              <span>{formError}</span>
            </div>
          )}

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Nama Item Koridor <span className="text-rose-500">*</span>
            </label>
            <input
              type="text"
              required
              placeholder="Contoh: Keset Koridor, Tempat Sampah Tambahan, Papan Informasi"
              value={formData.item_name}
              onChange={(e) => setFormData({ ...formData, item_name: e.target.value })}
              className="w-full px-3.5 py-2.5 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"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Jumlah (Unit / Titik)
            </label>
            <input
              type="number"
              min="0"
              placeholder="Kosongkan jika belum dihitung"
              value={formData.quantity}
              onChange={(e) => setFormData({ ...formData, quantity: e.target.value })}
              className="w-full px-3.5 py-2.5 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"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Kondisi Awal
            </label>
            <div className="grid grid-cols-3 gap-2">
              <button
                type="button"
                onClick={() => setFormData({ ...formData, condition: "belum" })}
                className={`py-2 px-3 rounded-xl text-xs font-semibold border transition-all cursor-pointer ${
                  formData.condition === "belum"
                    ? "bg-slate-800 text-white border-slate-800"
                    : "bg-slate-50 text-slate-700 border-slate-200 hover:bg-slate-100"
                }`}
              >
                Belum Diperiksa
              </button>
              <button
                type="button"
                onClick={() => setFormData({ ...formData, condition: "baik" })}
                className={`py-2 px-3 rounded-xl text-xs font-semibold border transition-all cursor-pointer ${
                  formData.condition === "baik"
                    ? "bg-emerald-600 text-white border-emerald-600"
                    : "bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-100"
                }`}
              >
                Kondisi Baik
              </button>
              <button
                type="button"
                onClick={() => setFormData({ ...formData, condition: "rusak" })}
                className={`py-2 px-3 rounded-xl text-xs font-semibold border transition-all cursor-pointer ${
                  formData.condition === "rusak"
                    ? "bg-rose-600 text-white border-rose-600"
                    : "bg-rose-50 text-rose-700 border-rose-200 hover:bg-rose-100"
                }`}
              >
                Kondisi Rusak
              </button>
            </div>
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Catatan Kondisi Fisik
            </label>
            <textarea
              rows={2}
              placeholder="Contoh: Lampu koridor dekat tangga berkedip, tegel retak"
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              className="w-full px-3.5 py-2.5 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 resize-none"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Rencana Tindak Lanjut
            </label>
            <textarea
              rows={2}
              placeholder="Contoh: Penggantian bohlam LED dan perbaikan tegel"
              value={formData.follow_up}
              onChange={(e) => setFormData({ ...formData, follow_up: e.target.value })}
              className="w-full px-3.5 py-2.5 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 resize-none"
            />
          </div>

          <div className="pt-2 flex items-center justify-end gap-2.5 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="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 disabled:opacity-50 cursor-pointer"
            >
              {isSubmitting ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Plus className="w-3.5 h-3.5" />}
              <span>Simpan Item Koridor</span>
            </button>
          </div>
        </form>
      </Modal>

      {/* ==================================================== */}
      {/* MODAL: EDIT ITEM KORIDOR */}
      {/* ==================================================== */}
      <Modal
        isOpen={isEditModalOpen}
        onClose={() => {
          setIsEditModalOpen(false);
          setActiveItem(null);
        }}
        title={`Edit Item Koridor: ${activeItem?.item_name || ""}`}
        description="Perbarui informasi fasilitas, status baik/rusak, dan tindak lanjut."
        maxWidth="max-w-lg"
      >
        <form onSubmit={handleSubmitEdit} className="space-y-4">
          {formError && (
            <div className="p-3 bg-rose-50 border border-rose-200 rounded-xl text-rose-700 text-xs font-medium flex items-center gap-2">
              <AlertTriangle className="w-4 h-4 shrink-0 text-rose-500" />
              <span>{formError}</span>
            </div>
          )}

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Nama Item Koridor <span className="text-rose-500">*</span>
            </label>
            <input
              type="text"
              required
              value={formData.item_name}
              onChange={(e) => setFormData({ ...formData, item_name: e.target.value })}
              className="w-full px-3.5 py-2.5 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"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Jumlah (Unit / Titik)
            </label>
            <input
              type="number"
              min="0"
              placeholder="Kosongkan jika belum dihitung"
              value={formData.quantity}
              onChange={(e) => setFormData({ ...formData, quantity: e.target.value })}
              className="w-full px-3.5 py-2.5 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"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Status Kondisi
            </label>
            <div className="grid grid-cols-3 gap-2">
              <button
                type="button"
                onClick={() => setFormData({ ...formData, condition: "belum" })}
                className={`py-2 px-3 rounded-xl text-xs font-semibold border transition-all cursor-pointer ${
                  formData.condition === "belum"
                    ? "bg-slate-800 text-white border-slate-800"
                    : "bg-slate-50 text-slate-700 border-slate-200 hover:bg-slate-100"
                }`}
              >
                Belum Diperiksa
              </button>
              <button
                type="button"
                onClick={() => setFormData({ ...formData, condition: "baik" })}
                className={`py-2 px-3 rounded-xl text-xs font-semibold border transition-all cursor-pointer ${
                  formData.condition === "baik"
                    ? "bg-emerald-600 text-white border-emerald-600"
                    : "bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-100"
                }`}
              >
                Kondisi Baik
              </button>
              <button
                type="button"
                onClick={() => setFormData({ ...formData, condition: "rusak" })}
                className={`py-2 px-3 rounded-xl text-xs font-semibold border transition-all cursor-pointer ${
                  formData.condition === "rusak"
                    ? "bg-rose-600 text-white border-rose-600"
                    : "bg-rose-50 text-rose-700 border-rose-200 hover:bg-rose-100"
                }`}
              >
                Kondisi Rusak
              </button>
            </div>
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Catatan Kondisi Fisik
            </label>
            <textarea
              rows={2}
              placeholder="Catatan kondisi fisik fasilitas..."
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              className="w-full px-3.5 py-2.5 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 resize-none"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-slate-700 mb-1">
              Rencana Tindak Lanjut
            </label>
            <textarea
              rows={2}
              placeholder="Rencana perbaikan atau pengadaan..."
              value={formData.follow_up}
              onChange={(e) => setFormData({ ...formData, follow_up: e.target.value })}
              className="w-full px-3.5 py-2.5 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 resize-none"
            />
          </div>

          <div className="pt-2 flex items-center justify-end gap-2.5 border-t border-slate-100">
            <button
              type="button"
              onClick={() => {
                setIsEditModalOpen(false);
                setActiveItem(null);
              }}
              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="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 disabled:opacity-50 cursor-pointer"
            >
              {isSubmitting ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Pencil className="w-3.5 h-3.5" />}
              <span>Simpan Perubahan</span>
            </button>
          </div>
        </form>
      </Modal>

      {/* ==================================================== */}
      {/* MODAL: HAPUS ITEM KORIDOR */}
      {/* ==================================================== */}
      <Modal
        isOpen={isDeleteModalOpen}
        onClose={() => {
          setIsDeleteModalOpen(false);
          setActiveItem(null);
        }}
        title="Hapus Item Koridor"
        description="Konfirmasi penghapusan fasilitas dari daftar kondisi koridor."
        maxWidth="max-w-md"
      >
        <div className="space-y-4">
          <p className="text-xs text-slate-600">
            Apakah Anda yakin ingin menghapus{" "}
            <span className="font-bold text-slate-900">&quot;{activeItem?.item_name}&quot;</span> dari daftar pemeriksaan Koridor Lantai {activeFloor}? Tindakan ini tidak dapat dibatalkan.
          </p>

          <div className="flex items-center justify-end gap-2.5 pt-2 border-t border-slate-100">
            <button
              type="button"
              onClick={() => {
                setIsDeleteModalOpen(false);
                setActiveItem(null);
              }}
              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="inline-flex items-center gap-1.5 px-4 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 cursor-pointer"
            >
              {isSubmitting ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Trash2 className="w-3.5 h-3.5" />}
              <span>Ya, Hapus Item</span>
            </button>
          </div>
        </div>
      </Modal>

      {/* ==================================================== */}
      {/* MODAL: PRATINJAU CETAK DOKUMEN REKAP KONDISI KORIDOR */}
      {/* ==================================================== */}
      <Modal
        isOpen={isPrintModalOpen}
        onClose={() => setIsPrintModalOpen(false)}
        title={`Pratinjau Cetak Kondisi Koridor Lantai ${activeFloor}`}
        description="Format lembar pemeriksaan resmi fasilitas koridor 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-corridor-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 KORIDOR LANTAI {activeFloor}
            </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">Lokasi Fasilitas:</span>
              <span className="font-bold text-slate-800">Koridor Lantai {activeFloor}</span>
            </div>
            <div>
              <span className="text-slate-500 block">Total Item Fasilitas:</span>
              <span className="font-bold text-slate-800">{corridorStats.total} Item</span>
            </div>
            <div>
              <span className="text-slate-500 block">Kondisi Baik:</span>
              <span className="font-bold text-emerald-700">{corridorStats.good} Item</span>
            </div>
            <div>
              <span className="text-slate-500 block">Kondisi Rusak / Perbaikan:</span>
              <span className="font-bold text-rose-700">{corridorStats.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 KORIDOR
                  </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 Wakasek Sarana (Muhammad Ridwanto, S.Pd) */}
          <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">
                {wakasekSarana.title || "Wakasek Bidang Sarana & Prasarana"}
              </p>
              <div
                style={{ height: "55px", minHeight: "55px" }}
                className="w-full flex items-center justify-center my-1"
              >
                {wakasekSarana.signature_image ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={wakasekSarana.signature_image}
                    alt="Tanda Tangan Wakasek Sarana"
                    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">
                {wakasekSarana.name && wakasekSarana.name !== "-"
                  ? wakasekSarana.name
                  : "Muhammad Ridwanto, S.Pd."}
              </p>
              <p className="text-[10px] text-slate-500 font-mono mt-0.5">
                {wakasekSarana.nip && wakasekSarana.nip !== "-"
                  ? wakasekSarana.nip.startsWith("NIP")
                    ? wakasekSarana.nip
                    : `NIPY. ${wakasekSarana.nip}`
                  : "NIPY. 10064"}
              </p>
            </div>
          </div>
        </div>
      </Modal>

    </div>
  );
};

export default CorridorConditionView;
