import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useCommandStore } from "@/lib/useCommandStore";

/**
 * Global keyboard shortcuts for WooNooW Admin SPA
 * - Blocks shortcuts while Command Palette is open
 * - Blocks single-key shortcuts when typing in inputs/contenteditable
 * - Keeps Cmd/Ctrl+K working everywhere to open the palette
 */
export function useShortcuts({ toggleFullscreen }: { toggleFullscreen?: () => void }) {
  const navigate = useNavigate();

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      const key = e.key.toLowerCase();
      const mod = e.metaKey || e.ctrlKey;

      // Always handle Command Palette toggle first so it works everywhere
      if (mod && key === "k") {
        e.preventDefault();
        try { useCommandStore.getState().toggle(); } catch { /* ignore if store not available */ }
        return;
      }

      // If Command Palette is open, ignore the rest
      try {
        if (useCommandStore.getState().open) return;
      } catch { /* ignore if store not available */ }

      // Do not trigger single-key shortcuts while typing
      const ae = (document.activeElement as HTMLElement | null);
      const isEditable = (el: Element | null) => {
        if (!el) return false;
        const tag = (el as HTMLElement).tagName;
        if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
        const h = el as HTMLElement;
        if (h.isContentEditable) return true;
        if (h.getAttribute('role') === 'combobox') return true;
        if (h.hasAttribute('cmdk-input')) return true; // cmdk input
        if (h.classList.contains('command-palette-search')) return true; // our class
        return false;
      };

      if (isEditable(ae) && !mod) {
        // Allow normal typing; only allow modified combos (handled above/below)
        return;
      }

      // Global Save: Ctrl/Cmd + S
      if (mod && key === "s") {
        e.preventDefault();
        window.dispatchEvent(new CustomEvent('woonoow:shortcut:save'));
        return;
      }

      // Fullscreen toggle: Ctrl/Cmd + Shift + F
      if (mod && e.shiftKey && key === "f") {
        e.preventDefault();
        toggleFullscreen?.();
        return;
      }

      // Quick Search: '/' focuses first search-like input (when not typing already)
      if (!mod && key === "/") {
        e.preventDefault();
        const input = document.querySelector<HTMLInputElement>('input[type="search"], input[placeholder*="search" i]');
        input?.focus();
        return;
      }

      // Navigation (single-key)
      if (!mod && !e.shiftKey) {
        switch (key) {
          case "d":
            e.preventDefault();
            navigate("/");
            return;
          case "o":
            e.preventDefault();
            navigate("/orders");
            return;
          case "r":
            e.preventDefault();
            window.location.reload();
            return;
        }
      }
    };

    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [navigate, toggleFullscreen]);
}