import { useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { COMMANDS } from "../lib/commands";
import { IconSearch } from "./icons";

export default function CommandPalette() {
  const navigate = useNavigate();
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(0);
  const rootRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const results = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return COMMANDS;
    return COMMANDS.filter((c) => `${c.label} ${c.section} ${c.keywords || ""}`.toLowerCase().includes(q));
  }, [query]);

  // Keep the active row in range as the result set changes.
  useEffect(() => {
    setActive(0);
  }, [query]);

  // Global Ctrl/⌘K to focus, Esc handled on the input.
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        inputRef.current?.focus();
        setOpen(true);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // Close when clicking outside.
  useEffect(() => {
    function onClick(e: MouseEvent) {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);

  function go(to: string) {
    navigate(to);
    setOpen(false);
    setQuery("");
    inputRef.current?.blur();
  }

  function onKeyDown(e: React.KeyboardEvent) {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActive((a) => Math.min(a + 1, results.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActive((a) => Math.max(a - 1, 0));
    } else if (e.key === "Enter") {
      e.preventDefault();
      if (results[active]) go(results[active].to);
    } else if (e.key === "Escape") {
      setOpen(false);
      inputRef.current?.blur();
    }
  }

  return (
    <div className="cmdk" ref={rootRef}>
      <div className="cmdk-field">
        <IconSearch />
        <input
          ref={inputRef}
          className="cmdk-input"
          placeholder="Search commands…"
          value={query}
          onFocus={() => setOpen(true)}
          onChange={(e) => setQuery(e.target.value)}
          onKeyDown={onKeyDown}
        />
        <kbd className="cmdk-kbd">⌘K</kbd>
      </div>

      {open && (
        <div className="cmdk-menu">
          {results.length === 0 ? (
            <div className="cmdk-empty">No matching commands</div>
          ) : (
            results.map((c, i) => (
              <button
                key={c.to}
                className={`cmdk-item ${i === active ? "active" : ""}`}
                onMouseEnter={() => setActive(i)}
                onMouseDown={(e) => {
                  e.preventDefault(); // keep focus so blur doesn't close before click
                  go(c.to);
                }}
              >
                <span className="cmdk-icon">{c.icon}</span>
                <span className="cmdk-label">{c.label}</span>
                <span className="cmdk-section">{c.section}</span>
              </button>
            ))
          )}
        </div>
      )}
    </div>
  );
}
