import { createSignal, For, onCleanup, onMount, Show } from "solid-js";
import { Search, X } from "lucide-solid";
import { useNavigate } from "@solidjs/router";

import { useApp } from "~/lib/app-context";

interface Command {
  id: string;
  label: string;
  shortcut?: string;
  action: () => void;
  category: string;
}

export function CommandPalette() {
  const app = useApp();
  const navigate = useNavigate();
  const [open, setOpen] = createSignal(false);
  const [query, setQuery] = createSignal("");

  const workspaceSlug = () => app.primaryWorkspace()?.slug ?? "personal";

  const commands: Command[] = [
    // Navigation
    { id: "nav-today", label: "Go to Today", shortcut: "G T", action: () => navigate(`/app/${workspaceSlug()}/today`), category: "Navigation" },
    { id: "nav-board", label: "Go to Board", shortcut: "G B", action: () => navigate(`/app/${workspaceSlug()}/board`), category: "Navigation" },
    { id: "nav-calendar", label: "Go to Calendar", shortcut: "G C", action: () => navigate(`/app/${workspaceSlug()}/calendar`), category: "Navigation" },
    { id: "nav-notes", label: "Go to Notes", shortcut: "G N", action: () => navigate(`/app/${workspaceSlug()}/notes`), category: "Navigation" },
    { id: "nav-contacts", label: "Go to Contacts", action: () => navigate(`/app/${workspaceSlug()}/contacts`), category: "Navigation" },
    { id: "nav-companies", label: "Go to Companies", action: () => navigate(`/app/${workspaceSlug()}/companies`), category: "Navigation" },
    { id: "nav-inbox", label: "Go to Inbox", action: () => navigate(`/app/${workspaceSlug()}/inbox`), category: "Navigation" },
    { id: "nav-focus", label: "Go to Focus", action: () => navigate(`/app/${workspaceSlug()}/focus`), category: "Navigation" },
    { id: "nav-settings", label: "Go to Settings", action: () => navigate(`/app/${workspaceSlug()}/settings`), category: "Navigation" },
    // Actions
    { id: "action-new-task", label: "Create new task", shortcut: "N T", action: () => navigate(`/app/${workspaceSlug()}/board`), category: "Actions" },
    { id: "action-new-event", label: "Create new event", action: () => navigate(`/app/${workspaceSlug()}/calendar`), category: "Actions" },
    { id: "action-new-contact", label: "Create new contact", action: () => navigate(`/app/${workspaceSlug()}/contacts`), category: "Actions" },
    { id: "action-new-company", label: "Create new company", action: () => navigate(`/app/${workspaceSlug()}/companies`), category: "Actions" },
    { id: "action-capture", label: "Quick capture", action: () => navigate(`/app/${workspaceSlug()}/inbox`), category: "Actions" },
    // Edit
    { id: "edit-undo", label: "Undo", shortcut: "Ctrl+Z", action: () => app.undo(), category: "Edit" },
    { id: "edit-redo", label: "Redo", shortcut: "Ctrl+Shift+Z", action: () => app.redo(), category: "Edit" },
    // Theme
    { id: "theme-toggle", label: "Toggle theme", action: () => app.toggleTheme(), category: "Preferences" },
  ];

  const filteredCommands = () => {
    const q = query().toLowerCase();
    if (!q) return commands;
    return commands.filter(c =>
      c.label.toLowerCase().includes(q) ||
      c.category.toLowerCase().includes(q)
    );
  };

  const handleKeyDown = (e: KeyboardEvent) => {
    // Open with Cmd/Ctrl + K
    if ((e.metaKey || e.ctrlKey) && e.key === "k") {
      e.preventDefault();
      setOpen(!open());
      setQuery("");
    }
    // Close with Escape
    if (e.key === "Escape" && open()) {
      setOpen(false);
    }
  };

  onMount(() => {
    window.addEventListener("keydown", handleKeyDown);
  });

  onCleanup(() => {
    window.removeEventListener("keydown", handleKeyDown);
  });

  const executeCommand = (cmd: Command) => {
    cmd.action();
    setOpen(false);
    setQuery("");
  };

  return (
    <Show when={open()}>
      <div class="fixed inset-0 z-50 flex items-start justify-center pt-[20vh]">
        {/* Backdrop */}
        <div
          class="absolute inset-0 bg-black/50 backdrop-blur-sm"
          onClick={() => setOpen(false)}
        />

        {/* Palette */}
        <div class="relative w-full max-w-xl bg-[var(--surface)] rounded-xl shadow-2xl border border-[var(--border)] overflow-hidden">
          {/* Search input */}
          <div class="flex items-center gap-3 px-4 py-3 border-b border-[var(--border)]">
            <Search class="w-5 h-5 text-[var(--text-muted)]" />
            <input
              type="text"
              value={query()}
              onInput={e => setQuery(e.currentTarget.value)}
              placeholder="Search commands..."
              class="flex-1 bg-transparent text-lg outline-none"
              autofocus
            />
            <kbd class="px-2 py-0.5 rounded bg-[var(--surface-hover)] text-xs text-[var(--text-muted)]">
              ESC
            </kbd>
          </div>

          {/* Commands list */}
          <div class="max-h-[60vh] overflow-auto p-2">
            <Show when={filteredCommands().length === 0}>
              <div class="text-center py-8 text-[var(--text-muted)]">
                No commands found
              </div>
            </Show>

            <For each={Object.groupBy(filteredCommands(), c => c.category)}>
              {([category, cmds]) => (
                <div class="mb-2">
                  <div class="px-2 py-1 text-xs font-medium text-[var(--text-muted)] uppercase">
                    {category}
                  </div>
                  <For each={cmds}>
                    {cmd => (
                      <button
                        onClick={() => executeCommand(cmd)}
                        class="w-full flex items-center justify-between px-3 py-2 rounded-lg hover:bg-[var(--surface-hover)] text-left"
                      >
                        <span>{cmd.label}</span>
                        <Show when={cmd.shortcut}>
                          <kbd class="px-2 py-0.5 rounded bg-[var(--surface-hover)] text-xs text-[var(--text-muted)]">
                            {cmd.shortcut}
                          </kbd>
                        </Show>
                      </button>
                    )}
                  </For>
                </div>
              )}
            </For>
          </div>

          {/* Footer */}
          <div class="px-4 py-2 border-t border-[var(--border)] text-xs text-[var(--text-muted)] flex items-center gap-4">
            <span><kbd class="px-1.5 py-0.5 rounded bg-[var(--surface-hover)]">↑↓</kbd> Navigate</span>
            <span><kbd class="px-1.5 py-0.5 rounded bg-[var(--surface-hover)]">↵</kbd> Select</span>
            <span><kbd class="px-1.5 py-0.5 rounded bg-[var(--surface-hover)]">ESC</kbd> Close</span>
          </div>
        </div>
      </div>
    </Show>
  );
}