import { useEffect } from 'react';
import { CommandInputHandle } from '../components/Terminal/CommandInput';

type AppView = 'terminal' | 'research' | 'settings';

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

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

interface UseAppShortcutsArgs {
  activeView: AppView;
  activeWorkspaceId: string;
  commandInputRef: React.RefObject<CommandInputHandle | null>;
  isProcessing: boolean;
  onClearTerminal: () => void;
  onCloseWorkspace: (workspaceId: string) => void;
  onCreateWorkspace: () => void;
  onOpenResearch: () => void;
  onOpenSettings: () => void;
  onToggleSidebar: () => void;
}

export const useAppShortcuts = ({
  activeView,
  activeWorkspaceId,
  commandInputRef,
  isProcessing,
  onClearTerminal,
  onCloseWorkspace,
  onCreateWorkspace,
  onOpenResearch,
  onOpenSettings,
  onToggleSidebar,
}: UseAppShortcutsArgs) => {
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (
        activeView === 'terminal' &&
        !isProcessing &&
        event.key === '/' &&
        !event.metaKey &&
        !event.ctrlKey &&
        !event.altKey &&
        !isEditableTarget(event.target)
      ) {
        event.preventDefault();
        commandInputRef.current?.focusWithText('/');
        return;
      }

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

      if ((event.metaKey || event.ctrlKey) && event.key === 'w') {
        event.preventDefault();
        onCloseWorkspace(activeWorkspaceId);
        return;
      }

      if ((event.metaKey || event.ctrlKey) && event.key === 'b') {
        event.preventDefault();
        onToggleSidebar();
        return;
      }

      if ((event.metaKey || event.ctrlKey) && event.key === 'l') {
        event.preventDefault();
        onClearTerminal();
        return;
      }

      if ((event.metaKey || event.ctrlKey) && event.key === ',') {
        event.preventDefault();
        onOpenSettings();
        return;
      }

      if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === 'r') {
        event.preventDefault();
        onOpenResearch();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [
    activeView,
    activeWorkspaceId,
    commandInputRef,
    isProcessing,
    onClearTerminal,
    onCloseWorkspace,
    onCreateWorkspace,
    onOpenResearch,
    onOpenSettings,
    onToggleSidebar,
  ]);
};
