"use client";

import { useRouter } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";

type SearchItem = { id: string; label: string; sublabel?: string; href: string };
type SearchSection = { kind: string; label: string; items: SearchItem[] };

const NAV_LINKS: SearchItem[] = [
  { id: "nav-dashboard", label: "Kontrolna tabla", sublabel: "/admin", href: "/admin" },
  { id: "nav-prijave", label: "Prijave", sublabel: "/admin/prijave", href: "/admin/prijave" },
  { id: "nav-kompanije", label: "Kompanije", sublabel: "/admin/kompanije", href: "/admin/kompanije" },
  { id: "nav-mesta", label: "Mesta", sublabel: "/admin/mesta", href: "/admin/mesta" },
  { id: "nav-recenzije", label: "Recenzije", sublabel: "/admin/recenzije", href: "/admin/recenzije" },
  { id: "nav-trust", label: "Trust & Safety", sublabel: "/admin/trust-safety", href: "/admin/trust-safety" },
  { id: "nav-naplata", label: "Naplata", sublabel: "/admin/naplata", href: "/admin/naplata" },
  { id: "nav-paketi", label: "Paketi i nivoi", sublabel: "/admin/paketi", href: "/admin/paketi" },
  { id: "nav-oglasi", label: "Oglasi", sublabel: "/admin/oglasi", href: "/admin/oglasi" },
  { id: "nav-aktivnosti", label: "Aktivnosti (audit)", sublabel: "/admin/aktivnosti", href: "/admin/aktivnosti" },
  { id: "nav-korisnici", label: "Korisnici", sublabel: "/admin/korisnici", href: "/admin/korisnici" },
  { id: "nav-podesavanja", label: "Podešavanja", sublabel: "/admin/podesavanja", href: "/admin/podesavanja" },
  // ── Entity graph (Sprint 1 — SEO + AIO) ─────────────────────────────────
  { id: "nav-industrije", label: "Industrije", sublabel: "/admin/industrije", href: "/admin/industrije" },
  { id: "nav-osobe", label: "Osobe (CEO/Founder)", sublabel: "/admin/osobe", href: "/admin/osobe" },
  { id: "nav-brendovi", label: "Brendovi", sublabel: "/admin/brendovi", href: "/admin/brendovi" },
  { id: "nav-autori", label: "Autori magazina", sublabel: "/admin/autori", href: "/admin/autori" },
  { id: "nav-ai-factory", label: "✨ AI Content Factory", sublabel: "/admin/magazin/ai-factory", href: "/admin/magazin/ai-factory" },
  { id: "nav-ai-suggestions", label: "💡 AI Predlozi članaka", sublabel: "/admin/magazin/predlozi", href: "/admin/magazin/predlozi" },
  { id: "nav-faq-db", label: "📚 FAQ baza", sublabel: "/admin/faq", href: "/admin/faq" },
  { id: "nav-web-vitals", label: "⚡ Web Vitals dashboard", sublabel: "/admin/web-vitals", href: "/admin/web-vitals" },
  { id: "nav-mediji", label: "📰 Mediji (Featured in)", sublabel: "/admin/mediji", href: "/admin/mediji" },
  { id: "nav-partneri", label: "🤝 Partneri", sublabel: "/admin/partneri", href: "/admin/partneri" },
  { id: "nav-kalendar", label: "📅 Editorial kalendar", sublabel: "/admin/magazin/kalendar", href: "/admin/magazin/kalendar" },
  { id: "nav-api-keys", label: "🔑 Open Data API ključevi", sublabel: "/admin/api-keys", href: "/admin/api-keys" },
];

const QUICK_ACTIONS: SearchItem[] = [
  { id: "act-new-company", label: "+ Nova kompanija", href: "/admin/kompanije/nova" },
  { id: "act-new-place", label: "+ Novo mesto", href: "/admin/mesta/nova" },
  { id: "act-new-event", label: "+ Novi događaj", href: "/admin/dogadjaji/nova" },
  { id: "act-new-real-estate", label: "+ Nova nekretnina", href: "/admin/nekretnine/nova" },
  { id: "act-new-car", label: "+ Novo vozilo", href: "/admin/automobili/nova" },
  { id: "act-new-job", label: "+ Novi posao", href: "/admin/poslovi/nova" },
  { id: "act-new-product", label: "+ Novi proizvod", href: "/admin/prodavnica/nova" },
  { id: "act-new-ad", label: "+ Postavi oglas ili isticanje", href: "/admin/oglasi/brzo" },
];

/**
 * Cmd+K (Mac) / Ctrl+K (Win/Linux) command palette za admin.
 *
 * Tri sekcije:
 *   • Brze akcije (statične)
 *   • Navigacija (statične rute)
 *   • Server pretraga (firme, nekretnine, vozila, prijave) — kada query ≥2 char
 *
 * Klijentski filter za nav i akcije, server fetch za entitete.
 */
export function AdminCommandPalette() {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [serverSections, setServerSections] = useState<SearchSection[]>([]);
  const [activeIdx, setActiveIdx] = useState(0);
  const inputRef = useRef<HTMLInputElement | null>(null);
  const debounceRef = useRef<number | null>(null);

  // Cmd/Ctrl+K toggle (desktop) + custom event listener (mobile bottom nav).
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      const isMod = e.metaKey || e.ctrlKey;
      if (isMod && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setOpen((v) => !v);
      } else if (e.key === "Escape" && open) {
        setOpen(false);
      }
    }
    function onCustomOpen() {
      setOpen(true);
    }
    window.addEventListener("keydown", onKey);
    window.addEventListener("admin:open-palette", onCustomOpen);
    return () => {
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("admin:open-palette", onCustomOpen);
    };
  }, [open]);

  // Focus input on open.
  useEffect(() => {
    if (open) {
      setQuery("");
      setActiveIdx(0);
      setServerSections([]);
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  }, [open]);

  // Debounced server search.
  useEffect(() => {
    if (debounceRef.current) window.clearTimeout(debounceRef.current);
    if (query.trim().length < 2) {
      setServerSections([]);
      return;
    }
    debounceRef.current = window.setTimeout(async () => {
      try {
        const res = await fetch(`/api/admin/search?q=${encodeURIComponent(query.trim())}`);
        if (!res.ok) return;
        const data = (await res.json()) as { sections: SearchSection[] };
        setServerSections(data.sections ?? []);
      } catch {
        /* noop */
      }
    }, 180);
    return () => {
      if (debounceRef.current) window.clearTimeout(debounceRef.current);
    };
  }, [query]);

  const filteredActions = useMemo(() => {
    const q = query.toLowerCase();
    if (!q) return QUICK_ACTIONS;
    return QUICK_ACTIONS.filter((a) => a.label.toLowerCase().includes(q));
  }, [query]);

  const filteredNav = useMemo(() => {
    const q = query.toLowerCase();
    if (!q) return NAV_LINKS;
    return NAV_LINKS.filter(
      (a) => a.label.toLowerCase().includes(q) || a.sublabel?.toLowerCase().includes(q),
    );
  }, [query]);

  const allSections: SearchSection[] = [
    ...(filteredActions.length ? [{ kind: "actions", label: "Brze akcije", items: filteredActions }] : []),
    ...(filteredNav.length ? [{ kind: "nav", label: "Navigacija", items: filteredNav }] : []),
    ...serverSections,
  ];
  const flatItems = allSections.flatMap((s) => s.items);

  function navigate(item: SearchItem) {
    setOpen(false);
    router.push(item.href);
  }

  function onKeyDown(e: React.KeyboardEvent) {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActiveIdx((i) => Math.min(flatItems.length - 1, i + 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveIdx((i) => Math.max(0, i - 1));
    } else if (e.key === "Enter") {
      e.preventDefault();
      const item = flatItems[activeIdx];
      if (item) navigate(item);
    }
  }

  if (!open) return null;

  let cursor = 0;

  return (
    <div className="fixed inset-0 z-[300] flex items-start justify-center bg-black/60 p-4 backdrop-blur-sm" onClick={() => setOpen(false)}>
      <div
        className="mt-[10vh] w-full max-w-xl overflow-hidden rounded-2xl border border-border bg-white shadow-[0_24px_60px_rgba(0,0,0,0.45)] dark:bg-zinc-950"
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
      >
        <div className="flex items-center gap-3 border-b border-border px-4 py-3">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" className="text-muted-foreground">
            <circle cx="11" cy="11" r="8" />
            <path d="m21 21-4.3-4.3" />
          </svg>
          <input
            ref={inputRef}
            value={query}
            onChange={(e) => {
              setQuery(e.target.value);
              setActiveIdx(0);
            }}
            onKeyDown={onKeyDown}
            placeholder="Skoči na stranicu, firmu, nekretninu, prijavu..."
            className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground"
          />
          <kbd className="rounded-md border border-border bg-zinc-50 px-1.5 py-0.5 text-[0.65rem] font-bold text-muted-foreground dark:bg-zinc-900">
            ESC
          </kbd>
        </div>

        <div className="max-h-[60vh] overflow-y-auto">
          {allSections.length === 0 ? (
            <div className="px-4 py-8 text-center text-sm text-muted-foreground">
              Nema rezultata za &bdquo;{query}&rdquo;.
            </div>
          ) : (
            allSections.map((section) => (
              <div key={section.kind} className="border-b border-border last:border-b-0">
                <p className="px-4 pt-3 text-[0.62rem] font-extrabold uppercase tracking-[0.18em] text-muted-foreground">
                  {section.label}
                </p>
                <ul className="py-1">
                  {section.items.map((item) => {
                    const idx = cursor++;
                    const active = idx === activeIdx;
                    return (
                      <li key={item.id}>
                        <button
                          type="button"
                          onMouseEnter={() => setActiveIdx(idx)}
                          onClick={() => navigate(item)}
                          className={`flex w-full items-start gap-3 px-4 py-2.5 text-left transition ${
                            active
                              ? "bg-primary/10 text-primary"
                              : "text-foreground hover:bg-zinc-50 dark:hover:bg-zinc-900"
                          }`}
                        >
                          <div className="min-w-0 flex-1">
                            <div className="truncate text-sm font-medium">{item.label}</div>
                            {item.sublabel && (
                              <div className="truncate text-xs text-muted-foreground">
                                {item.sublabel}
                              </div>
                            )}
                          </div>
                          {active && (
                            <kbd className="rounded-md border border-border bg-white px-1.5 py-0.5 text-[0.6rem] font-bold text-muted-foreground dark:bg-zinc-900">
                              ↵
                            </kbd>
                          )}
                        </button>
                      </li>
                    );
                  })}
                </ul>
              </div>
            ))
          )}
        </div>

        <div className="flex items-center justify-between border-t border-border bg-zinc-50 px-4 py-2 text-[0.7rem] text-muted-foreground dark:bg-zinc-900">
          <span>Cmd/Ctrl + K za otvaranje</span>
          <span>↑↓ navigacija · ↵ otvori</span>
        </div>
      </div>
    </div>
  );
}
