import React, { useCallback } from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { useNavigate, useLocation } from 'react-router-dom';
import { useHotkeyStore, useHotkeysEnabled } from '@/stores/hotkeyStore';
import { shortcuts, navigationRoutes } from '@/lib/keyboardShortcuts';
import { CommandPalette } from './CommandPalette';
import { ShortcutsHelpModal } from './ShortcutsHelpModal';

interface HotkeyProviderProps {
  children: React.ReactNode;
}

/**
 * HotkeyProvider - Global keyboard shortcut handler
 * Wraps the application and provides keyboard navigation
 */
export function HotkeyProvider({ children }: HotkeyProviderProps) {
  const navigate = useNavigate();
  const location = useLocation();
  const hotkeysEnabled = useHotkeysEnabled();

  const {
    openCommandPalette,
    closeCommandPalette,
    commandPaletteOpen,
    openShortcutsHelp,
    closeShortcutsHelp,
    shortcutsHelpOpen,
    addRecentCommand,
  } = useHotkeyStore();

  // Helper to check if we're in an input field
  const isInputFocused = useCallback(() => {
    const activeElement = document.activeElement;
    if (!activeElement) return false;

    const tagName = activeElement.tagName.toLowerCase();
    const isInput = tagName === 'input' || tagName === 'textarea';
    const isContentEditable = activeElement.getAttribute('contenteditable') === 'true';

    return isInput || isContentEditable;
  }, []);

  // Command palette toggle (Cmd+K)
  useHotkeys(
    shortcuts.openCommandPalette.keys,
    (e) => {
      e.preventDefault();
      if (hotkeysEnabled) {
        openCommandPalette();
      }
    },
    {
      enableOnFormTags: false,
      enableOnContentEditable: false,
    }
  );

  // Shortcuts help (Cmd+/)
  useHotkeys(
    shortcuts.showShortcuts.keys,
    (e) => {
      e.preventDefault();
      if (hotkeysEnabled && !commandPaletteOpen) {
        openShortcutsHelp();
      }
    },
    {
      enableOnFormTags: false,
      enableOnContentEditable: false,
    }
  );

  // Escape to close modals
  useHotkeys(
    'escape',
    () => {
      if (commandPaletteOpen) {
        closeCommandPalette();
      } else if (shortcutsHelpOpen) {
        closeShortcutsHelp();
      }
    },
    {
      enableOnFormTags: true,
    }
  );

  // Navigation shortcuts (G then X pattern)
  // These use sequence keys
  const navigationShortcuts = Object.entries(navigationRoutes);

  navigationShortcuts.forEach(([shortcutId, route]) => {
    const shortcut = shortcuts[shortcutId];
    if (shortcut) {
      // eslint-disable-next-line react-hooks/rules-of-hooks
      useHotkeys(
        shortcut.keys,
        (e) => {
          e.preventDefault();
          if (hotkeysEnabled && !commandPaletteOpen && !isInputFocused()) {
            navigate(route);
            addRecentCommand({ id: shortcutId, label: shortcut.label });
          }
        },
        {
          enableOnFormTags: false,
          enableOnContentEditable: false,
        }
      );
    }
  });

  // Handle command execution from palette
  const handleCommandExecute = useCallback(
    (commandId: string, route?: string) => {
      if (route) {
        navigate(route);
      }
      const shortcut = shortcuts[commandId];
      if (shortcut) {
        addRecentCommand({ id: commandId, label: shortcut.label });
      }
    },
    [navigate, addRecentCommand]
  );

  return (
    <>
      {children}
      <CommandPalette
        open={commandPaletteOpen}
        onClose={closeCommandPalette}
        onExecute={handleCommandExecute}
        currentPath={location.pathname}
      />
      <ShortcutsHelpModal
        open={shortcutsHelpOpen}
        onClose={closeShortcutsHelp}
      />
    </>
  );
}

export default HotkeyProvider;
