import { useEffect } from 'react';
import type { WorkspaceViewKind } from '../types/research';

const viewOrder: WorkspaceViewKind[] = [
  'canvas',
  'kanban',
  'graph',
  'thesis_builder',
  'memo_drafting',
  'evidence_trace',
  'catalyst_risk_map',
  'timeline',
  'model',
];

interface UseResearchKeyboardArgs {
  enabled: boolean;
  onFocusCapture: () => void;
  onOpenSearch: () => void;
  onOpenMemo: () => void;
  onOpenTerminal?: () => void;
  onArchiveSelection: () => void;
  onPinSelection: () => void;
  onSelectView: (view: WorkspaceViewKind) => void;
  onCycleGhost: (direction: -1 | 1) => void;
}

const isEditableTarget = (target: EventTarget | null) => {
  if (!(target instanceof HTMLElement)) {
    return false;
  }

  return (
    target.isContentEditable ||
    target.tagName === 'INPUT' ||
    target.tagName === 'TEXTAREA' ||
    target.tagName === 'SELECT'
  );
};

export const useResearchKeyboard = ({
  enabled,
  onFocusCapture,
  onOpenSearch,
  onOpenMemo,
  onOpenTerminal,
  onArchiveSelection,
  onPinSelection,
  onSelectView,
  onCycleGhost,
}: UseResearchKeyboardArgs) => {
  useEffect(() => {
    if (!enabled) {
      return;
    }

    const handleKeyDown = (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
        event.preventDefault();
        onOpenSearch();
        return;
      }

      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 't') {
        event.preventDefault();
        onOpenTerminal?.();
        return;
      }

      if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === 'm') {
        event.preventDefault();
        onOpenMemo();
        return;
      }

      if (isEditableTarget(event.target)) {
        return;
      }

      if (event.key === '/') {
        event.preventDefault();
        onFocusCapture();
        return;
      }

      if (event.key === 'p' || event.key === 'P') {
        event.preventDefault();
        onPinSelection();
        return;
      }

      if (event.key === 'a' || event.key === 'A') {
        event.preventDefault();
        onArchiveSelection();
        return;
      }

      if (event.key === '[') {
        event.preventDefault();
        onCycleGhost(-1);
        return;
      }

      if (event.key === ']') {
        event.preventDefault();
        onCycleGhost(1);
        return;
      }

      const viewIndex = Number.parseInt(event.key, 10);
      if (!Number.isNaN(viewIndex) && viewIndex >= 1 && viewIndex <= viewOrder.length) {
        event.preventDefault();
        onSelectView(viewOrder[viewIndex - 1]);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [
    enabled,
    onArchiveSelection,
    onCycleGhost,
    onFocusCapture,
    onOpenMemo,
    onOpenSearch,
    onOpenTerminal,
    onPinSelection,
    onSelectView,
  ]);
};
