import { useEffect } from 'react'
import { useSpotlightStore } from '../state/spotlightStore'

export const useKeyboardShortcuts = (handlers: {
  onOpenSpotlight: () => void
  onCloseSpotlight: () => void
  onNavigateUp: () => void
  onNavigateDown: () => void
  onNavigateLeft: () => void
  onNavigateRight: () => void
  onSelect: () => void
}) => {
  const { open, sel, setSel } = useSpotlightStore()

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.ctrlKey || e.metaKey || e.altKey) return

      if (open) {
        if (e.key === 'Escape') {
          handlers.onCloseSpotlight()
          return
        }

        if (e.key === 'ArrowDown') {
          e.preventDefault()
          setSel(Math.min(sel + 1, useSpotlightStore.getState().results.length - 1))
          return
        }

        if (e.key === 'ArrowUp') {
          e.preventDefault()
          setSel(Math.max(0, sel - 1))
          return
        }

        if (e.key === 'PageDown') {
          e.preventDefault()
          setSel(Math.min(sel + 10, useSpotlightStore.getState().results.length - 1))
          return
        }

        if (e.key === 'PageUp') {
          e.preventDefault()
          setSel(Math.max(0, sel - 10))
          return
        }

        if (e.key === 'Home') {
          e.preventDefault()
          setSel(0)
          return
        }

        if (e.key === 'End') {
          e.preventDefault()
          setSel(useSpotlightStore.getState().results.length - 1)
          return
        }

        if (e.key === 'Enter') {
          handlers.onSelect()
          return
        }
      }

      if (!open) {
        switch (e.key) {
          case 'k':
            handlers.onNavigateUp()
            break
          case 'j':
            handlers.onNavigateDown()
            break
          case 'h':
            handlers.onNavigateLeft()
            break
          case 'l':
            handlers.onNavigateRight()
            break
        }
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [open, sel, handlers, setSel])
}
