import { useEffect } from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { useHotkeyStore, useHotkeysEnabled } from '@/stores/hotkeyStore';
import { shortcuts } from '@/lib/keyboardShortcuts';

interface HotkeyAction {
  /** Shortcut ID from keyboardShortcuts registry */
  shortcutId: string;
  /** Action to execute when shortcut is triggered */
  action: () => void;
  /** Optional condition - if false, shortcut is disabled */
  enabled?: boolean;
}

interface UsePageHotkeysOptions {
  /** Enable shortcuts only when this element is focused */
  scope?: string;
  /** Disable shortcuts in form elements */
  enableOnFormTags?: boolean;
}

/**
 * usePageHotkeys - Hook for registering page-specific keyboard shortcuts
 *
 * Usage:
 * usePageHotkeys([
 *   { shortcutId: 'newInvoice', action: () => setModalOpen(true) },
 *   { shortcutId: 'saveDraft', action: handleSave, enabled: isDirty },
 * ]);
 */
export function usePageHotkeys(
  actions: HotkeyAction[],
  options: UsePageHotkeysOptions = {}
) {
  const hotkeysEnabled = useHotkeysEnabled();
  const { commandPaletteOpen, shortcutsHelpOpen, setActiveContext } = useHotkeyStore();

  const { enableOnFormTags = false } = options;

  // Set active context when component mounts
  useEffect(() => {
    setActiveContext('page');
    return () => setActiveContext('global');
  }, [setActiveContext]);

  // Register each hotkey
  actions.forEach(({ shortcutId, action, enabled = true }) => {
    const shortcut = shortcuts[shortcutId];

    // eslint-disable-next-line react-hooks/rules-of-hooks
    useHotkeys(
      shortcut?.keys || '',
      (e) => {
        e.preventDefault();
        if (
          hotkeysEnabled &&
          enabled &&
          !commandPaletteOpen &&
          !shortcutsHelpOpen &&
          shortcut
        ) {
          action();
        }
      },
      {
        enableOnFormTags,
        enableOnContentEditable: false,
        enabled: hotkeysEnabled && enabled && !commandPaletteOpen && !shortcutsHelpOpen,
      },
      [hotkeysEnabled, enabled, commandPaletteOpen, shortcutsHelpOpen, action]
    );
  });
}

/**
 * useSingleHotkey - Hook for a single keyboard shortcut
 *
 * Usage:
 * useSingleHotkey('newInvoice', () => setModalOpen(true));
 */
export function useSingleHotkey(
  shortcutId: string,
  action: () => void,
  enabled: boolean = true
) {
  usePageHotkeys([{ shortcutId, action, enabled }]);
}

/**
 * useFormHotkeys - Hook for form-specific shortcuts (like Cmd+S to save)
 * Enables shortcuts even when form elements are focused
 */
export function useFormHotkeys(actions: HotkeyAction[]) {
  const hotkeysEnabled = useHotkeysEnabled();
  const { commandPaletteOpen, shortcutsHelpOpen, setActiveContext } = useHotkeyStore();

  useEffect(() => {
    setActiveContext('form');
    return () => setActiveContext('global');
  }, [setActiveContext]);

  actions.forEach(({ shortcutId, action, enabled = true }) => {
    const shortcut = shortcuts[shortcutId];

    // eslint-disable-next-line react-hooks/rules-of-hooks
    useHotkeys(
      shortcut?.keys || '',
      (e) => {
        e.preventDefault();
        if (
          hotkeysEnabled &&
          enabled &&
          !commandPaletteOpen &&
          !shortcutsHelpOpen &&
          shortcut
        ) {
          action();
        }
      },
      {
        enableOnFormTags: true, // Enable in forms
        enableOnContentEditable: true,
        enabled: hotkeysEnabled && enabled && !commandPaletteOpen && !shortcutsHelpOpen,
      },
      [hotkeysEnabled, enabled, commandPaletteOpen, shortcutsHelpOpen, action]
    );
  });
}

export default usePageHotkeys;
