import { useState } from "react";
import { useApi, apiFetch } from "../hooks/useApi.js";
import DeviceCard from "../components/DeviceCard.jsx";

export default function DeviceLibrary() {
  const { data: devices, loading, error, refetch } = useApi("/devices");
  const [search, setSearch] = useState("");

  const handleNuke = async (mac) => {
    if (!confirm(`NUKE device ${mac}? This will block all internet access.`)) return;
    try {
      await apiFetch(`/devices/${encodeURIComponent(mac)}/nuke`, { method: "POST" });
      refetch();
    } catch (err) {
      console.error("Nuke failed:", err);
    }
  };

  const handleUnnuke = async (mac) => {
    try {
      await apiFetch(`/devices/${encodeURIComponent(mac)}/unnuke`, { method: "POST" });
      refetch();
    } catch (err) {
      console.error("Unnuke failed:", err);
    }
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-40 gap-4">
        <div className="w-8 h-8 border-2 border-gold/30 border-t-gold rounded-full animate-spin" />
        <span className="text-gold/50 text-[0.6rem] tracking-[0.4em] uppercase font-bold">Scanning Estate Perimeter...</span>
      </div>
    );
  }

  const deviceList = Array.isArray(devices) ? devices : [];
  const filtered = deviceList.filter((d) => {
    const term = search.toLowerCase();
    const name = (d.name || d.hostname || d.oui || "").toLowerCase();
    const mac = (d.mac || "").toLowerCase();
    const ip = (d.ip || "").toLowerCase();
    return name.includes(term) || mac.includes(term) || ip.includes(term);
  });

  return (
    <div className="space-y-8 pb-10">
      <header className="flex flex-col items-center pt-2">
        <div className="w-12 h-px bg-gold/30 mb-4" />
        <h1 className="font-serif text-3xl md:text-4xl font-bold text-cream tracking-tight text-center">
          Device <span className="text-gold italic">Inventory</span>
        </h1>
        <p className="text-[0.55rem] text-cream-dark tracking-[0.5em] uppercase mt-2 opacity-50 font-bold">Total Clients: {deviceList.length}</p>
      </header>

      <div className="space-y-6">
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between px-1">
           <div className="relative w-full sm:w-72">
             <input
               type="text"
               placeholder="SEARCH BY NAME, IP, OR MAC..."
               value={search}
               onChange={(e) => setSearch(e.target.value)}
               className="manor-input w-full pl-4 pr-10 py-2.5 text-[0.65rem] tracking-widest placeholder:opacity-30"
             />
             <div className="absolute right-3 top-1/2 -translate-y-1/2 text-gold opacity-30">
               <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
             </div>
           </div>
           <button onClick={refetch} className="text-[0.55rem] text-gold/60 hover:text-gold tracking-[0.2em] uppercase transition-colors flex items-center gap-2">
             <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M23 4v6h-6"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
             Refresh scan
           </button>
        </div>

        {filtered.length === 0 ? (
          <div className="glass-card p-20 text-center flex flex-col items-center gap-4 opacity-40">
             <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" className="text-gold"><circle cx="12" cy="12" r="10"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
             <span className="text-[0.65rem] tracking-[0.3em] uppercase">No entities located</span>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {filtered.map((device) => (
              <DeviceCard
                key={device.mac || device._id}
                device={device}
                onNuke={() => handleNuke(device.mac)}
                onUnnuke={() => handleUnnuke(device.mac)}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
