import { useEffect } from 'react';
import { useSitesStore } from '@/store/sites.ts';
import { useCoverageStore } from '@/store/coverage.ts';
import { useSettingsStore } from '@/store/settings.ts';
import { useToastStore } from '@/components/ui/Toast.tsx';

interface ShortcutHandlers {
  onCalculate: () => void;
  onCloseForm: () => void;
  onShowShortcuts?: () => void;
}

function isInputActive(): boolean {
  const el = document.activeElement;
  if (!el) return false;
  const tag = el.tagName;
  return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
}

export function useKeyboardShortcuts({
  onCalculate,
  onCloseForm,
  onShowShortcuts,
}: ShortcutHandlers) {
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      const isMac = navigator.platform.toLowerCase().includes('mac');
      const modKey = isMac ? e.metaKey : e.ctrlKey;

      // === Modifier shortcuts (work even in inputs) ===
      if (modKey && e.key === 'Enter') {
        e.preventDefault();
        onCalculate();
        return;
      }

      // Escape always works
      if (e.key === 'Escape') {
        useSitesStore.getState().selectSite(null);
        useSitesStore.getState().setPlacingMode(false);
        onCloseForm();
        return;
      }

      // === Skip remaining shortcuts if typing in an input ===
      if (isInputActive()) return;

      // Shift combos (no browser conflicts)
      if (e.shiftKey && !modKey && !e.altKey) {
        switch (e.key.toUpperCase()) {
          case 'S': // Shift+S: New site (place mode)
            e.preventDefault();
            useSitesStore.getState().setPlacingMode(true);
            useToastStore.getState().addToast('Click on map to place new site', 'info');
            return;
          case 'C': // Shift+C: Clear coverage
            e.preventDefault();
            useCoverageStore.getState().clearCoverage();
            useToastStore.getState().addToast('Coverage cleared', 'info');
            return;
        }
      }

      // Single letter shortcuts (no modifiers)
      if (!modKey && !e.altKey && !e.shiftKey) {
        switch (e.key.toLowerCase()) {
          case 'h': // H: Toggle heatmap
            useCoverageStore.getState().toggleHeatmap();
            return;
          case 'g': // G: Toggle grid
            useSettingsStore.getState().setShowGrid(
              !useSettingsStore.getState().showGrid
            );
            return;
          case 't': // T: Toggle terrain
            useSettingsStore.getState().setShowElevationOverlay(
              !useSettingsStore.getState().showElevationOverlay
            );
            return;
          case 'r': // R: Toggle ruler / measurement
            useSettingsStore.getState().setMeasurementMode(
              !useSettingsStore.getState().measurementMode
            );
            return;
          case 'f': // F: Fit to coverage — dispatch custom event for Map.tsx to handle
            window.dispatchEvent(new CustomEvent('rfcp:fit-bounds'));
            return;
          case 'delete': // Delete key: delete selected site with undo
          case 'backspace':
            {
              const selectedId = useSitesStore.getState().selectedSiteId;
              if (selectedId) {
                const site = useSitesStore.getState().sites.find(s => s.id === selectedId);
                if (site) {
                  // Snapshot for undo
                  const snapshot = { ...site };
                  useSitesStore.getState().deleteSite(selectedId);
                  useToastStore.getState().addToast(`"${site.name}" deleted`, 'info', {
                    duration: 10000,
                    action: {
                      label: 'Undo',
                      onClick: async () => {
                        await useSitesStore.getState().addSite({
                          name: snapshot.name,
                          lat: snapshot.lat,
                          lon: snapshot.lon,
                          height: snapshot.height,
                          power: snapshot.power,
                          gain: snapshot.gain,
                          frequency: snapshot.frequency,
                          antennaType: snapshot.antennaType,
                          azimuth: snapshot.azimuth,
                          beamwidth: snapshot.beamwidth,
                          color: snapshot.color,
                          visible: snapshot.visible,
                          notes: snapshot.notes,
                          equipment: snapshot.equipment,
                        });
                        useToastStore.getState().addToast(`"${snapshot.name}" restored`, 'success');
                      },
                    },
                  });
                }
              }
            }
            return;
        }

        // ? key for help (not shift on some layouts)
        if (e.key === '?') {
          onShowShortcuts?.();
          return;
        }
      }

      // ? with shift (most layouts: shift+/)
      if (e.shiftKey && !modKey && !e.altKey && e.key === '?') {
        onShowShortcuts?.();
        return;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onCalculate, onCloseForm, onShowShortcuts]);
}
