import { useEffect, RefObject } from 'react';

export interface VideoPlayerRef {
  togglePlay: () => void;
  seekForward: (seconds: number) => void;
  seekBackward: (seconds: number) => void;
  toggleMute: () => void;
  toggleFullscreen: () => void;
}

export interface UseKeyboardShortcutsOptions {
  playerRef: RefObject<VideoPlayerRef>;
  onClose?: () => void;
  enabled?: boolean;
}

/**
 * Custom hook for video player keyboard shortcuts
 *
 * Shortcuts:
 * - Space: Toggle play/pause
 * - Left Arrow: Seek backward 5 seconds
 * - Right Arrow: Seek forward 5 seconds
 * - M: Toggle mute
 * - F: Toggle fullscreen
 * - Escape: Close video (if onClose provided)
 */
export function useKeyboardShortcuts({
  playerRef,
  onClose,
  enabled = true,
}: UseKeyboardShortcutsOptions) {
  useEffect(() => {
    if (!enabled) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      // Don't trigger shortcuts if user is typing in an input
      const target = e.target as HTMLElement;
      if (
        target.tagName === 'INPUT' ||
        target.tagName === 'TEXTAREA' ||
        target.isContentEditable
      ) {
        // Allow ESC even in inputs
        if (e.key !== 'Escape') {
          return;
        }
      }

      const player = playerRef.current;
      if (!player) return;

      switch (e.key) {
        case 'Escape':
          e.preventDefault();
          onClose?.();
          break;

        case ' ':
          e.preventDefault();
          player.togglePlay();
          break;

        case 'ArrowLeft':
          e.preventDefault();
          player.seekBackward(5);
          break;

        case 'ArrowRight':
          e.preventDefault();
          player.seekForward(5);
          break;

        case 'm':
        case 'M':
          e.preventDefault();
          player.toggleMute();
          break;

        case 'f':
        case 'F':
          e.preventDefault();
          player.toggleFullscreen();
          break;

        default:
          // Do nothing for other keys
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [enabled, playerRef, onClose]);
}
