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

import React from "react";
import { User } from "../types";
import { X, ShieldAlert, Award, Clock, Eye, AlertCircle } from "lucide-react";
import { getApiUrl } from "../utils";

interface QuickLoginModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelectUser: (user: User) => void;
}

export default function QuickLoginModal({ isOpen, onClose, onSelectUser }: QuickLoginModalProps) {
  const [demoUsers, setDemoUsers] = React.useState<User[]>([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (isOpen) {
      setLoading(true);
      fetch(getApiUrl("admin/users"))
        .then(res => res.json())
        .then(data => {
          setDemoUsers(data);
          setLoading(false);
        })
        .catch(err => {
          console.error("Gagal memuat pengguna untuk demo", err);
          setLoading(false);
        });
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const categories = [
    { title: "Siswa (Pemohon Izin)", role: "siswa", desc: "Melakukan request/pengajuan izin keluar sekolah" },
    { title: "Guru Mata Pelajaran (Verifikator 1)", role: "guru_mapel", desc: "Verifikasi akademik tingkat pertama sebelum murid diijinkan meninggalkan kelas" },
    { title: "Guru Piket (Verifikator 2)", role: "guru_piket", desc: "Persetujuan administratif tingkat dua di meja piket sekolah" },
    { title: "Satpam / Security Gate (Validator Akhir)", role: "satpam", desc: "Validasi gerbang jam keluar sesungguhnya dan jam kembali siswa" },
    { title: "Administrator (Tata Usaha)", role: "admin", desc: "Manajemen user, data impor/ekspor, & cetak laporan formal mingguan/bulanan" }
  ];

  return (
    <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center z-50 p-4 animate-fade-in print:hidden">
      <div className="bg-white w-full max-w-4xl rounded-2xl shadow-2xl flex flex-col max-h-[90vh]">
        {/* Modal Header */}
        <div className="flex justify-between items-center px-6 py-4 border-b border-gray-100 bg-gray-50/50 rounded-t-2xl">
          <div className="flex items-center space-x-2">
            <span className="p-1.5 bg-blue-100 rounded-lg text-blue-900">
              <ShieldAlert className="h-5 w-5" />
            </span>
            <div>
              <h2 className="text-base font-bold text-gray-900">Pilih Peran Akun (Simulator Alur)</h2>
              <p className="text-xs text-gray-500 font-sans">Klik pada salah satu akun untuk login instan & menguji alur izin sekolah SMAN 1 Bantaran</p>
            </div>
          </div>
          <button id="quick-login-close" onClick={onClose} className="p-1.5 hover:bg-gray-100 rounded-lg text-gray-400 hover:text-gray-900">
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Modal Body */}
        <div className="flex-1 overflow-y-auto p-6 space-y-6">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-12">
              <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-blue-900"></div>
              <p className="text-sm text-gray-500 mt-4">Memuat data verifikator untuk simulator...</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {categories.map((cat, idx) => {
                const members = demoUsers.filter(u => u.role === cat.role);
                return (
                  <div key={idx} className="bg-slate-50 border border-slate-200/60 rounded-xl p-4 flex flex-col">
                    <div className="mb-3">
                      <h3 className="text-sm font-bold text-gray-900 flex items-center gap-1.5">
                        <span className="h-2 w-2 rounded-full bg-blue-900 inline-block"></span>
                        {cat.title}
                      </h3>
                      <p className="text-[11px] text-gray-500 mt-0.5">{cat.desc}</p>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 mt-auto">
                      {members.length > 0 ? (
                        members.map(user => (
                          <button
                            key={user.id}
                            id={`quick-user-${user.username}`}
                            onClick={() => onSelectUser(user)}
                            className="bg-white hover:bg-blue-50/30 hover:border-blue-300 border border-gray-200 text-left p-2.5 rounded-lg transition-all shadow-2xs hover:shadow-xs group"
                          >
                            <p className="text-xs font-bold text-gray-800 truncate group-hover:text-blue-900">{user.name}</p>
                            <p className="text-[10px] text-gray-400 font-mono mt-0.5 truncate bg-gray-50 px-1 py-0.5 rounded">
                              un: <strong className="text-gray-600 font-medium">{user.username}</strong> | pw: <strong className="text-gray-600 font-medium">{(user as any).password || "123"}</strong>
                            </p>
                            {user.siswaClass && (
                              <p className="text-[10px] text-blue-850 font-semibold mt-1">Kelas {user.siswaClass}</p>
                            )}
                          </button>
                        ))
                      ) : (
                        <span className="text-xs text-amber-600 bg-amber-50 px-2.5 py-1 rounded border border-amber-200 col-span-2 flex items-center gap-1.5">
                          <AlertCircle className="h-3.5 w-3.5" />
                          Tidak ada data. Tambah di Admin.
                        </span>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Modal Footer */}
        <div className="px-6 py-4 border-t border-gray-100 bg-gray-50 flex justify-end rounded-b-2xl">
          <p className="text-xs text-gray-400 font-mono self-center mr-auto">SMAN 1 BANTARAN • 2026</p>
          <button
            id="quick-login-btn-close-footer"
            onClick={onClose}
            className="px-4 py-2 bg-gray-205 hover:bg-gray-300 text-gray-800 text-xs font-semibold rounded-lg transition-colors border border-gray-300 cursor-pointer"
          >
            Tutup
          </button>
        </div>
      </div>
    </div>
  );
}
