'use client'

import { useEffect, useCallback } from 'react'

interface UseKeyboardProps {
  onNext: () => void
  onPrev: () => void
  onFirst: () => void
  onLast: () => void
  onOverview: () => void
  onFullscreen: () => void
  onLanguageToggle: () => void
  onMenuToggle: () => void
  onPresenterToggle?: () => void
  onGoToSlide: (index: number) => void
  enabled?: boolean
}

export function useKeyboard({
  onNext,
  onPrev,
  onFirst,
  onLast,
  onOverview,
  onFullscreen,
  onLanguageToggle,
  onMenuToggle,
  onPresenterToggle,
  onGoToSlide,
  enabled = true,
}: UseKeyboardProps) {
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (!enabled) return

      const target = e.target as HTMLElement
      if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
        return
      }

      switch (e.key) {
        case 'ArrowRight':
        case ' ':
        case 'Enter':
          e.preventDefault()
          onNext()
          break
        case 'ArrowLeft':
          e.preventDefault()
          onPrev()
          break
        case 'Escape':
          e.preventDefault()
          onOverview()
          break
        case 'f':
        case 'F':
          e.preventDefault()
          onFullscreen()
          break
        case 'Home':
          e.preventDefault()
          onFirst()
          break
        case 'End':
          e.preventDefault()
          onLast()
          break
        case 'l':
        case 'L':
          e.preventDefault()
          onLanguageToggle()
          break
        case 'm':
        case 'M':
          e.preventDefault()
          onMenuToggle()
          break
        case 'p':
        case 'P':
          e.preventDefault()
          onPresenterToggle?.()
          break
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
          e.preventDefault()
          onGoToSlide(parseInt(e.key) - 1)
          break
      }
    },
    [enabled, onNext, onPrev, onFirst, onLast, onOverview, onFullscreen, onLanguageToggle, onMenuToggle, onPresenterToggle, onGoToSlide]
  )

  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [handleKeyDown])
}
