import { useEffect } from 'react';

import { getClientOs } from 'src/utils/platform';
import { logEvent } from 'src/config/amplitude';
import {
  EventName,
  ShiftManagementMenuOption,
  ShiftManagementMenuSource,
} from 'src/types/amplitude';

type UseShiftsKeyboardShortcutsProps = {
  onCopy: () => void;
  onPaste: () => void;
  clearSelection: () => void;
  showRemoveShiftsConfirmationModal: () => void;
  isDeletingShifts: boolean;
  areShiftsSelected: boolean;
  /** Called when the user presses Cmd/Ctrl+A */
  onSelectAll: () => void;
  /** When true, next Ctrl+A will deselect all; used to log SELECT_ALL vs UNSELECT_ALL */
  isEverythingSelected: boolean;
  disabled?: boolean;
  clearSelectedCells: () => void;
  /** Close contextual overlays (menus, popovers, etc.) */
  closeOpenOverlays: () => void;
};

export const useShiftsKeyboardShortcuts = ({
  onCopy,
  onPaste,
  clearSelection,
  showRemoveShiftsConfirmationModal,
  isDeletingShifts,
  areShiftsSelected,
  onSelectAll,
  isEverythingSelected,
  disabled = false,
  clearSelectedCells,
  closeOpenOverlays,
}: UseShiftsKeyboardShortcutsProps) => {
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      // Don't trigger shortcuts if disabled (e.g., during coachmark)
      if (disabled) {
        return;
      }

      const target = event.target as HTMLElement;
      const isTextInput =
        (target.tagName === 'INPUT' &&
          (target as HTMLInputElement).type !== 'checkbox') ||
        target.tagName === 'TEXTAREA';
      // Don't trigger if user is typing in a text input
      if (isTextInput || target.isContentEditable) {
        return;
      }

      const isCmdOrCtrl = !event.shiftKey && (event.metaKey || event.ctrlKey);

      if (isCmdOrCtrl && event.key === 'c') {
        event.preventDefault();
        logEvent(EventName.SHIFT_MANAGEMENT_MENU_USED, {
          option_used: ShiftManagementMenuOption.COPY,
          menu: ShiftManagementMenuSource.KEYBOARD,
        });
        onCopy();
      }

      if (isCmdOrCtrl && event.key === 'v') {
        event.preventDefault();
        logEvent(EventName.SHIFT_MANAGEMENT_MENU_USED, {
          option_used: ShiftManagementMenuOption.PASTE,
          menu: ShiftManagementMenuSource.KEYBOARD,
        });
        onPaste();
      }

      if (isCmdOrCtrl && event.key === 'a') {
        event.preventDefault();
        logEvent(EventName.SHIFT_MANAGEMENT_MENU_USED, {
          option_used: isEverythingSelected
            ? ShiftManagementMenuOption.UNSELECT_ALL
            : ShiftManagementMenuOption.SELECT_ALL,
          menu: ShiftManagementMenuSource.KEYBOARD,
        });
        onSelectAll();
      }

      if (event.key === 'Escape') {
        event.preventDefault();
        closeOpenOverlays();
        // Always clear all selections (not just copy/paste)
        // This ensures Escape works consistently regardless of selection state
        clearSelection();
        clearSelectedCells();
      }

      const isDeleteKey =
        event.key === 'Delete' ||
        (event.key === 'Backspace' && getClientOs() === 'MacOS');

      // Show confirmation modal for deleting selected shifts
      if (areShiftsSelected && isDeleteKey && !isDeletingShifts) {
        event.preventDefault();
        logEvent(EventName.SHIFT_MANAGEMENT_MENU_USED, {
          option_used: ShiftManagementMenuOption.REMOVE_SHIFT,
          menu: ShiftManagementMenuSource.KEYBOARD,
        });
        showRemoveShiftsConfirmationModal();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [
    onCopy,
    onPaste,
    clearSelection,
    showRemoveShiftsConfirmationModal,
    isDeletingShifts,
    areShiftsSelected,
    onSelectAll,
    isEverythingSelected,
    disabled,
    clearSelectedCells,
    closeOpenOverlays,
  ]);
};
