/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React from "react";
import { User, Permit } from "../types";
import { formatIndonesianDate, getApiUrl } from "../utils";
import { ShieldCheck, LogOut, ArrowRightLeft, UserCheck, Search, Loader2, Compass, Home, DoorOpen } from "lucide-react";

interface DashboardSatpamProps {
  currentUser: User;
  refreshPermitsTrigger: () => void;
  allPermits: Permit[];
}

export default function DashboardSatpam({ currentUser, refreshPermitsTrigger, allPermits }: DashboardSatpamProps) {
  const [searchTerm, setSearchTerm] = React.useState("");
  const [loadingId, setLoadingId] = React.useState<string | null>(null);

  // Filter 1: Ready to Checkout (Mapel and Piket fully approved)
  const readyToLeave = allPermits.filter(
    p => p.overallStatus === "approved_to_leave"
  );

  // Filter 2: Currently Off-campus (checked out, waiting for return)
  const activeOutside = allPermits.filter(
    p => p.overallStatus === "checked_out"
  );

  const handleCheckout = async (permitId: string) => {
    setLoadingId(permitId);
    try {
      const res = await fetch(getApiUrl(`permits/${permitId}/checkout`), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ satpamId: currentUser.id, satpamName: currentUser.name })
      });
      if (!res.ok) throw new Error("Gagal memvalidasi keluar");
      refreshPermitsTrigger();
    } catch (err) {
      alert("Error: " + err);
    } finally {
      setLoadingId(null);
    }
  };

  const handleCheckin = async (permitId: string) => {
    setLoadingId(permitId);
    try {
      const res = await fetch(getApiUrl(`permits/${permitId}/checkin`), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ satpamId: currentUser.id, satpamName: currentUser.name })
      });
      if (!res.ok) throw new Error("Gagal memvalidasi kembali");
      refreshPermitsTrigger();
    } catch (err) {
      alert("Error: " + err);
    } finally {
      setLoadingId(null);
    }
  };

  const filterList = (list: Permit[]) => {
    if (!searchTerm.trim()) return list;
    const s = searchTerm.toLowerCase();
    return list.filter(
      p => p.siswaName.toLowerCase().includes(s) || p.siswaInduk.includes(s) || p.siswaClass.toLowerCase().includes(s)
    );
  };

  const outListFiltered = filterList(readyToLeave);
  const backListFiltered = filterList(activeOutside);

  return (
    <div className="space-y-8 animate-fade-in text-slate-800">
      {/* Header Guard Banner */}
      <div className="bg-slate-900 text-white p-6 rounded-2xl flex flex-wrap justify-between items-center gap-4 border border-slate-800 shadow-sm">
        <div className="flex items-center space-x-3">
          <div className="bg-indigo-600 text-white p-2.5 rounded-xl font-bold">
            <ShieldCheck className="h-6 w-6" />
          </div>
          <div>
            <h2 className="text-base font-bold">POS GERBANG UTAMA SMAN 1 BANTARAN</h2>
            <p className="text-xs text-slate-400 font-sans mt-0.5">Petugas: <strong>{currentUser.name} (NIP/ID: {currentUser.indukNumber})</strong></p>
          </div>
        </div>

        {/* Global Search Bar */}
        <div className="relative w-full sm:w-72">
          <Search className="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Cari Siswa... (Nama / NISN / Kelas)"
            className="w-full bg-slate-800/80 border border-slate-705 rounded-lg pl-9 pr-3 py-2 text-xs text-white placeholder-slate-400 focus:outline-hidden focus:border-indigo-500 font-sans"
          />
        </div>
      </div>

      {/* Grid: Left - Waiting for Gate Out, Right - Currently outside */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        
        {/* STREAM 1: MENUNGGU VALIDASI LOG KELUAR */}
        <div className="space-y-4">
          <div>
            <span className="text-mono text-[10px] uppercase font-bold text-indigo-700 bg-indigo-50 px-2 py-0.5 rounded border border-indigo-200">Tahap Keluar</span>
            <h3 className="text-base font-bold text-slate-900 mt-1 flex items-center gap-1.5">
              <DoorOpen className="h-4 w-4 text-indigo-600" />
              Siswa Siap Meninggalkan Sekolah
            </h3>
            <p className="text-xs text-slate-500 font-sans">Siswa yang sudah disetujui Guru Mapel & Piket, sedang mengantre di pos satpam untuk keluar sekolah.</p>
          </div>

          {outListFiltered.length === 0 ? (
            <div className="bg-white border border-slate-200 rounded-2xl p-8 text-center text-slate-450 font-sans shadow-sm">
              Tidak ada siswa yang terverifikasi siap keluar saat ini.
            </div>
          ) : (
            <div className="space-y-4">
              {outListFiltered.map(p => (
                <div key={p.id} className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm hover:shadow-md transition-all relative overflow-hidden">
                  <div className="absolute left-0 top-0 bottom-0 w-1.5 bg-indigo-600"></div>
                  
                  <div className="flex justify-between items-start mb-2 border-b border-slate-100 pb-2">
                    <div>
                      <span className="text-xs font-bold text-indigo-600 font-mono">{p.siswaClass}</span>
                      <h4 className="text-sm font-bold text-slate-900 mt-0.5">{p.siswaName}</h4>
                      <p className="text-[10px] text-slate-400 font-mono">NISN: {p.siswaInduk}</p>
                    </div>
                    <span className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                      p.permitType === "keluar_masuk" ? "bg-indigo-50 text-indigo-700" : "bg-amber-50 text-amber-800"
                    }`}>
                      {p.permitType === "keluar_masuk" ? "Izin Sementara" : "Pulang Cepat"}
                    </span>
                  </div>

                  <div className="space-y-1.5 text-xs text-slate-650 mt-2 font-sans">
                    <p>🕒 <span className="font-bold text-slate-700">Rencana:</span> {p.timeExitProposed} s/d {p.timeReturnProposed || "Selesai"}</p>
                    <p>📝 <span className="font-bold text-slate-700">Keperluan:</span> <span className="italic">"{p.reason}"</span></p>
                    <div className="grid grid-cols-2 gap-2 text-[10px] mt-2 bg-slate-50 p-2 rounded border border-slate-100">
                      <div>
                        <span className="text-slate-400 uppercase tracking-widest block font-bold">Verifikator 1:</span>
                        <span className="font-semibold text-emerald-800">✓ {p.mapelTeacherName}</span>
                      </div>
                      <div>
                        <span className="text-slate-400 uppercase tracking-widest block font-bold">Verifikator 2:</span>
                        <span className="font-semibold text-emerald-800">✓ {p.piketTeacherName}</span>
                      </div>
                    </div>
                  </div>

                  <button
                    id={`satpam-btn-checkout-${p.id}`}
                    disabled={loadingId !== null}
                    onClick={() => handleCheckout(p.id)}
                    className="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-2.5 rounded-lg text-xs mt-4 transition-colors flex items-center justify-center gap-1.5 cursor-pointer shadow-sm"
                  >
                    {loadingId === p.id ? (
                      <Loader2 className="h-4 w-4 animate-spin text-white" />
                    ) : (
                      <LogOut className="h-4 w-4" />
                    )}
                    Validasi & Buka Gerbang Keluar
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* STREAM 2: SEDANG DILUAR - MENUNGGU GERBANG KEMBALI */}
        <div className="space-y-4">
          <div>
            <span className="text-mono text-[10px] uppercase font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200">Keluar Kampus</span>
            <h3 className="text-base font-bold text-slate-900 mt-1 flex items-center gap-1.5">
              <Compass className="h-4 w-4 text-emerald-600" />
              Siswa Sedang Berada di Luar Sekolah
            </h3>
            <p className="text-xs text-slate-500 font-sans">Siswa pemegang izin ("Keluar Masuk") yang sedang diluar, ketuk tombol begitu mereka masuk kembali.</p>
          </div>

          {backListFiltered.length === 0 ? (
            <div className="bg-white border border-slate-200 rounded-2xl p-8 text-center text-slate-450 font-sans shadow-sm">
              Tidak ada siswa yang aktif diluar sekolah dengan izin kembali.
            </div>
          ) : (
            <div className="space-y-4">
              {backListFiltered.map(p => (
                <div key={p.id} className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm hover:shadow-md transition-all relative overflow-hidden">
                  <div className="absolute left-0 top-0 bottom-0 w-1.5 bg-emerald-500"></div>

                  <div className="flex justify-between items-start mb-2 border-b border-slate-100 pb-2">
                    <div>
                      <span className="text-xs font-bold text-emerald-700 font-mono">{p.siswaClass}</span>
                      <h4 className="text-sm font-bold text-slate-900 mt-0.5">{p.siswaName}</h4>
                      <p className="text-[10px] text-slate-400 font-mono">NISN: {p.siswaInduk}</p>
                    </div>
                    <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-50 text-amber-800 border border-amber-200 font-mono">
                      Target Kembali: {p.timeReturnProposed}
                    </span>
                  </div>

                  <div className="space-y-1.5 text-xs text-slate-650 mt-2 font-sans">
                    <p>🚪 <span className="font-bold text-indigo-700">Meninggalkan Kampus Jam:</span> <strong className="font-mono text-slate-900">{p.timeCheckedOut}</strong></p>
                    <p>📝 <span className="font-bold text-slate-700">Alasan Izin:</span> <span className="italic">"{p.reason}"</span></p>
                    <p className="text-[10px] text-slate-400">Verifikator Piket: {p.piketTeacherName}</p>
                  </div>

                  <button
                    id={`satpam-btn-checkin-${p.id}`}
                    disabled={loadingId !== null}
                    onClick={() => handleCheckin(p.id)}
                    className="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-semibold py-2.5 rounded-lg text-xs mt-4 transition-colors flex items-center justify-center gap-1.5 cursor-pointer shadow-sm"
                  >
                    {loadingId === p.id ? (
                      <Loader2 className="h-4 w-4 animate-spin text-white" />
                    ) : (
                      <UserCheck className="h-4 w-4" />
                    )}
                    Siswa Kembali, Tutup Surat Izin
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

      </div>
    </div>
  );
}
