"use client";

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

import { getNavItems } from "@/lib/nav";
import { OPTIONS_DASHBOARDS } from "@/features/options/options-config";
import { PERPS_DASHBOARDS } from "@/features/perps/perps-config";
import { useHotkey } from "@/lib/hooks/use-hotkey";

type PaletteItem = {
  label: string;
  href: string;
  type: string;
};

function buildItems(microstructureEnabled: boolean): PaletteItem[] {
  const items: PaletteItem[] = [];
  for (const nav of getNavItems(microstructureEnabled)) {
    items.push({ label: nav.label, href: nav.href, type: "page" });
  }
  for (const dash of OPTIONS_DASHBOARDS) {
    items.push({ label: dash.title, href: `/options/${dash.id}`, type: "dashboard" });
  }
  for (const dash of PERPS_DASHBOARDS) {
    items.push({ label: `${dash.title} (Perps)`, href: `/perps/${dash.id}`, type: "dashboard" });
  }
  return items;
}

export function CommandPalette({ microstructureEnabled }: { microstructureEnabled: boolean }) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [activeIndex, setActiveIndex] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const router = useRouter();

  const items = useMemo(() => buildItems(microstructureEnabled), [microstructureEnabled]);
  const filtered = useMemo(() => {
    if (!query) return items;
    const q = query.toLowerCase();
    return items.filter((item) => item.label.toLowerCase().includes(q));
  }, [items, query]);

  const toggle = useCallback(() => {
    setOpen((prev) => {
      if (!prev) {
        setQuery("");
        setActiveIndex(0);
      }
      return !prev;
    });
  }, []);

  useHotkey("k", toggle, { meta: true });

  useEffect(() => {
    if (open) {
      requestAnimationFrame(() => inputRef.current?.focus());
    }
  }, [open]);

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

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === "Escape") {
      setOpen(false);
    } else if (e.key === "ArrowDown") {
      e.preventDefault();
      setActiveIndex((i) => Math.min(i + 1, filtered.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveIndex((i) => Math.max(i - 1, 0));
    } else if (e.key === "Enter" && filtered[activeIndex]) {
      navigate(filtered[activeIndex].href);
    }
  }

  if (!open) return null;

  return (
    <div className="commandBackdrop" onClick={() => setOpen(false)}>
      <div className="commandPalette" onClick={(e) => e.stopPropagation()} onKeyDown={handleKeyDown}>
        <input
          ref={inputRef}
          className="commandInput"
          placeholder="Search pages, dashboards..."
          value={query}
          onChange={(e) => {
            setQuery(e.target.value);
            setActiveIndex(0);
          }}
        />
        <div className="commandList">
          {filtered.map((item, i) => (
            <div
              key={item.href}
              className={`commandItem ${i === activeIndex ? "commandItemActive" : ""}`}
              onClick={() => navigate(item.href)}
              onMouseEnter={() => setActiveIndex(i)}
            >
              <span>{item.label}</span>
              <span className="commandItemType">{item.type}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
