import { useCallback } from 'react';
import type { EditableTableState } from '../../state/EditableTable';
import type { FiltersMap } from '@wix/bex-core';

export function useKeyboardNavigation<T, F extends FiltersMap>(
  state: EditableTableState<T, F>,
) {
  const { cellInteraction, clipboard } = state;

  const onKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      const { focusedCell, isEditing } = cellInteraction;
      if (!focusedCell) {
        return;
      }

      // Don't intercept keys when editing (let the editor handle them)
      if (isEditing) {
        if (e.key === 'Escape') {
          e.preventDefault();
          cellInteraction.cancelEdit();
        } else if (e.key === 'Tab') {
          e.preventDefault();
          cellInteraction.commitEdit();
          if (e.shiftKey) {
            cellInteraction.moveToPreviousCell();
          } else {
            cellInteraction.moveToNextCell();
          }
          cellInteraction.scrollFocusedCellIntoView();
        }
        return;
      }

      const isCtrlOrCmd = e.ctrlKey || e.metaKey;
      const extend = e.shiftKey;
      let navigated = false;

      switch (e.key) {
        case 'ArrowUp':
          e.preventDefault();
          cellInteraction.moveFocus('up', extend);
          navigated = true;
          break;
        case 'ArrowDown':
          e.preventDefault();
          cellInteraction.moveFocus('down', extend);
          navigated = true;
          break;
        case 'ArrowLeft':
          e.preventDefault();
          cellInteraction.moveFocus('left', extend);
          navigated = true;
          break;
        case 'ArrowRight':
          e.preventDefault();
          cellInteraction.moveFocus('right', extend);
          navigated = true;
          break;
        case 'Tab':
          e.preventDefault();
          if (e.shiftKey) {
            cellInteraction.moveToPreviousCell();
          } else {
            cellInteraction.moveToNextCell();
          }
          navigated = true;
          break;
        case 'Escape': {
          const handledByEditor = e.defaultPrevented;
          e.preventDefault();
          if (clipboard.hasCopiedCells) {
            clipboard.clear();
          } else if (!handledByEditor) {
            cellInteraction.clearFocus();
          }
          break;
        }
        case 'Delete':
        case 'Backspace':
          e.preventDefault();
          if (!state.updateItemDisabled) {
            state.clearCells(cellInteraction.selectedCellsList);
          }
          break;
        case 'a':
          if (isCtrlOrCmd) {
            e.preventDefault();
            cellInteraction.selectAll();
          }
          break;
        default:
          break;
      }

      if (navigated) {
        cellInteraction.scrollFocusedCellIntoView();
      }
    },
    [cellInteraction, clipboard, state],
  );

  return { onKeyDown };
}
