"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { DOMAINS } from "@/lib/sag/domains";
import { KNOWN_LICENSES } from "@/lib/sag/licenses-seed";
import { SEED_FILINGS } from "@/lib/sag/filings-seed";
import { PITCHES } from "@/lib/sag/pitches";
import { AGENT_LIST } from "@/lib/sag/agents";

type ResultKind = "entity" | "domain" | "license" | "filing" | "pitch" | "agent" | "page";

interface Result {
  kind: ResultKind;
  label: string;
  sublabel?: string;
  href: string;
  hint?: string;
}

const PAGE_ROUTES: Result[] = [
  { kind: "page", label: "Dashboard", href: "/app/dashboard", hint: "🏠" },
  { kind: "page", label: "Entities", href: "/app/entities", hint: "🏢" },
  { kind: "page", label: "Cash position", href: "/app/finance", hint: "💰" },
  { kind: "page", label: "Bills inbox", href: "/app/finance/bills", hint: "🧾" },
  { kind: "page", label: "Annual budget", href: "/app/finance/budget", hint: "📊" },
  { kind: "page", label: "Toast POS", href: "/app/toast", hint: "🍞" },
  { kind: "page", label: "Compliance", href: "/app/compliance", hint: "📋" },
  { kind: "page", label: "Filings", href: "/app/compliance/filings", hint: "🗓️" },
  { kind: "page", label: "Licenses", href: "/app/compliance/licenses", hint: "📜" },
  { kind: "page", label: "Domains", href: "/app/domains", hint: "🌐" },
  { kind: "page", label: "HR", href: "/app/hr", hint: "👥" },
  { kind: "page", label: "Social calendar", href: "/app/social", hint: "📣" },
  { kind: "page", label: "Documents", href: "/app/docs", hint: "📁" },
  { kind: "page", label: "Crowdfund", href: "/app/crowdfund", hint: "🚀" },
  { kind: "page", label: "Connections", href: "/app/settings/connections", hint: "🔌" },
  { kind: "page", label: "Backup & restore", href: "/app/settings/data", hint: "💾" },
];

export function GlobalSearch() {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [activeIdx, setActiveIdx] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const router = useRouter();

  // Keyboard listener for Cmd/Ctrl+K
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setOpen((v) => !v);
      }
      if (e.key === "Escape" && open) {
        setOpen(false);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  useEffect(() => {
    // Defer state updates by a tick to avoid sync-setState-in-effect lint
    const t = setTimeout(() => {
      if (open) {
        setActiveIdx(0);
        inputRef.current?.focus();
      } else {
        setQuery("");
      }
    }, 0);
    return () => clearTimeout(t);
  }, [open]);

  const results = useMemo<Result[]>(() => {
    const q = query.trim().toLowerCase();
    if (!q) {
      // Default: show entities + agents
      return [
        ...ALL_ORGANIZATIONS.slice(0, 6).map((o) => ({
          kind: "entity" as const,
          label: o.name,
          sublabel: o.industry,
          href: `/app/entities/${o.slug}`,
          hint: o.emoji,
        })),
        ...AGENT_LIST.map((a) => ({
          kind: "agent" as const,
          label: a.name,
          sublabel: a.subtitle,
          href: `/app/agents/${a.id}`,
          hint: a.icon,
        })),
      ];
    }

    const r: Result[] = [];
    const pushIfMatch = (label: string, item: Result) => {
      if (label.toLowerCase().includes(q)) r.push(item);
    };

    for (const o of ALL_ORGANIZATIONS) {
      pushIfMatch(o.name, {
        kind: "entity",
        label: o.name,
        sublabel: `${o.industry} · ${o.entityType}`,
        href: `/app/entities/${o.slug}`,
        hint: o.emoji,
      });
    }
    for (const d of DOMAINS) {
      pushIfMatch(d.domain, {
        kind: "domain",
        label: d.domain,
        sublabel: d.category,
        href: `/app/domains`,
        hint: "🌐",
      });
    }
    for (const l of KNOWN_LICENSES) {
      pushIfMatch(l.licenseType, {
        kind: "license",
        label: l.licenseType,
        sublabel: l.agency,
        href: `/app/compliance/licenses`,
        hint: "📜",
      });
    }
    for (const f of SEED_FILINGS) {
      pushIfMatch(f.filingType, {
        kind: "filing",
        label: f.filingType,
        sublabel: `${f.agency} · ${f.cadence}`,
        href: `/app/compliance/filings`,
        hint: "🗓️",
      });
    }
    for (const p of PITCHES) {
      pushIfMatch(p.legalEntity, {
        kind: "pitch",
        label: p.legalEntity.replace(/, LLC$/, ""),
        sublabel: "Reg CF pitch + Form C",
        href: `/app/crowdfund/${p.slug}/form-c`,
        hint: p.emoji,
      });
    }
    for (const a of AGENT_LIST) {
      pushIfMatch(a.name, {
        kind: "agent",
        label: a.name,
        sublabel: a.subtitle,
        href: `/app/agents/${a.id}`,
        hint: a.icon,
      });
    }
    for (const pr of PAGE_ROUTES) {
      pushIfMatch(pr.label, pr);
    }

    return r.slice(0, 30);
  }, [query]);

  function go(idx: number) {
    const r = results[idx];
    if (!r) return;
    setOpen(false);
    router.push(r.href);
  }

  function onKey(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActiveIdx((i) => Math.min(i + 1, results.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveIdx((i) => Math.max(i - 1, 0));
    } else if (e.key === "Enter") {
      e.preventDefault();
      go(activeIdx);
    }
  }

  if (!open) {
    return (
      <button
        onClick={() => setOpen(true)}
        className="inline-flex items-center gap-2 rounded-md border bg-background px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent"
        title="Search (⌘K)"
      >
        <span>🔍</span>
        <span className="hidden sm:inline">Search</span>
        <kbd className="hidden sm:inline-flex items-center gap-1 rounded border bg-muted px-1.5 py-0.5 font-mono text-[10px]">
          ⌘K
        </kbd>
      </button>
    );
  }

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center pt-[12vh] bg-background/60 backdrop-blur-sm" onClick={() => setOpen(false)}>
      <div
        className="w-full max-w-2xl rounded-lg border bg-background shadow-2xl overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center gap-3 border-b px-4 py-3">
          <span className="text-lg">🔍</span>
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => {
              setQuery(e.target.value);
              setActiveIdx(0);
            }}
            onKeyDown={onKey}
            placeholder="Search entities, domains, filings, licenses, pitches, agents..."
            className="flex-1 bg-transparent outline-none text-sm"
          />
          <kbd className="rounded border bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">ESC</kbd>
        </div>
        <div className="max-h-[60vh] overflow-y-auto">
          {results.length === 0 ? (
            <div className="p-8 text-center text-sm text-muted-foreground">No matches.</div>
          ) : (
            <ul>
              {results.map((r, i) => (
                <li key={`${r.kind}-${r.href}-${i}`}>
                  <button
                    onClick={() => go(i)}
                    onMouseEnter={() => setActiveIdx(i)}
                    className={`w-full flex items-center gap-3 px-4 py-2.5 text-left text-sm transition-colors ${
                      i === activeIdx ? "bg-accent" : ""
                    }`}
                  >
                    <span className="text-base shrink-0">{r.hint ?? "·"}</span>
                    <div className="min-w-0 flex-1">
                      <div className="font-medium truncate">{r.label}</div>
                      {r.sublabel && <div className="text-xs text-muted-foreground truncate">{r.sublabel}</div>}
                    </div>
                    <span className="section-label">{r.kind}</span>
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>
        <div className="border-t bg-muted/30 px-4 py-2 text-[10px] text-muted-foreground flex items-center justify-between gap-3">
          <span>↑↓ navigate · ↵ open · ESC close</span>
          <div className="flex items-center gap-3">
            <span>{results.length} results</span>
            <button
              type="button"
              onClick={() => {
                const q = query.trim();
                setOpen(false);
                router.push(q ? `/app/search?q=${encodeURIComponent(q)}` : "/app/search");
              }}
              className="text-foreground hover:underline"
            >
              View all results →
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
