"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useSearch, type SearchResult } from "@lynkd/messaging-inbox-sdk";
import { useUi } from "@/lib/ui-state";
import { Search, Hash, User, MessageSquare, FileText, LifeBuoy, CornerDownLeft, Inbox } from "lucide-react";
import clsx from "clsx";

const icons: Record<SearchResult["type"], typeof Hash> = {
  channel: Hash, person: User, message: MessageSquare, file: FileText, ticket: LifeBuoy,
};

type Item = { key: string; icon: typeof Hash; title: string; subtitle?: string; run: () => void };

export function CommandPalette() {
  const { paletteOpen, setPaletteOpen, openProfile, openThread } = useUi();
  const { query, setQuery, results, loading } = useSearch();
  const router = useRouter();
  const [active, setActive] = useState(0);
  const listRef = useRef<HTMLDivElement>(null);

  const go = (r: SearchResult) => {
    setPaletteOpen(false);
    if (r.type === "person") openProfile(r.id);
    else if (r.type === "ticket") router.push(`/support/${r.id}`);
    else if (r.type === "message" && r.channelId) {
      // a reply lives inside a thread (not the main list) → open the thread;
      // otherwise deep-link so the channel view scrolls to + flashes it
      if (r.parentId) { router.push(`/c/${r.channelId}`); openThread(r.channelId, r.parentId); }
      else router.push(`/c/${r.channelId}?msg=${r.id}`);
    }
    else if (r.channelId) router.push(`/c/${r.channelId}`);
  };

  const items: Item[] = useMemo(() => {
    if (!query) {
      return [
        { key: "q1", icon: Hash, title: "Jump to #general", run: () => { setPaletteOpen(false); router.push("/c/c_general"); } },
        { key: "q2", icon: Inbox, title: "Open Inbox", run: () => { setPaletteOpen(false); router.push("/inbox"); } },
        { key: "q3", icon: LifeBuoy, title: "Support Center", run: () => { setPaletteOpen(false); router.push("/support"); } },
      ];
    }
    if (loading) return [];
    return results.map((r) => ({ key: `${r.type}-${r.id}`, icon: icons[r.type], title: r.title, subtitle: r.subtitle, run: () => go(r) }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [query, loading, results]);

  useEffect(() => { setActive(0); }, [query, results]);

  if (!paletteOpen) return null;

  const onKey = (e: React.KeyboardEvent) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setActive((a) => Math.min(a + 1, items.length - 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setActive((a) => Math.max(a - 1, 0)); }
    else if (e.key === "Enter") { e.preventDefault(); items[active]?.run(); }
  };

  return (
    <div className="fixed inset-0 z-[60] flex items-start justify-center bg-black/50 p-4 pt-[12vh] backdrop-blur-sm animate-fade-in" onClick={() => setPaletteOpen(false)}>
      <div role="dialog" aria-modal="true" aria-label="Search" className="w-full max-w-xl overflow-hidden rounded-card border border-border bg-elevated shadow-pop" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center gap-3 border-b border-border px-4">
          <Search size={18} className="text-muted" />
          <input
            autoFocus
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={onKey}
            placeholder="Search messages, channels, people, tickets…"
            className="w-full bg-transparent py-4 text-[15px] outline-none placeholder:text-dim"
          />
          <kbd className="rounded bg-hover px-1.5 py-0.5 font-mono text-[10px] text-dim">esc</kbd>
        </div>

        <div ref={listRef} className="max-h-[52vh] overflow-y-auto p-2">
          {!query && <div className="px-2 py-1 text-[11px] font-bold uppercase text-dim">Quick actions</div>}
          {query && loading && <div className="px-3 py-6 text-center text-[13px] text-muted">Searching…</div>}
          {query && !loading && items.length === 0 && <div className="px-3 py-6 text-center text-[13px] text-muted">No results for “{query}”</div>}
          {items.map((it, i) => (
            <button
              key={it.key}
              onMouseEnter={() => setActive(i)}
              onClick={it.run}
              className={clsx("flex w-full items-center gap-3 rounded-control px-3 py-2 text-left", i === active ? "bg-hover" : "hover:bg-hover")}
            >
              <span className="grid h-8 w-8 shrink-0 place-items-center rounded-control bg-hover text-muted"><it.icon size={16} /></span>
              <span className="min-w-0 flex-1">
                <span className="block truncate text-[14px] text-ink">{it.title}</span>
                {it.subtitle && <span className="block truncate text-[12px] text-muted">{it.subtitle}</span>}
              </span>
              {i === active && <CornerDownLeft size={14} className="shrink-0 text-dim" />}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
