import { useState, useEffect, useCallback, useRef } from 'react'
import { usePhotoStore } from '../store/photoStore'

/**
 * Keyboard navigation for card grids (tags, colors, ratings, people).
 *
 * Arrow keys move the active index through the grid (wrapping at row
 * boundaries based on the actual CSS column count), Enter opens the
 * selected card, and Escape / Backspace exits the detail view.
 *
 * In detail mode, Escape only exits back to the card grid when the
 * preview is closed and no photos are selected — otherwise it defers
 * to Timeline's own Escape handler (clear selection / close preview).
 *
 * The grid container ref is used to measure the rendered column count
 * so up/down navigation stays column-aligned.
 */
export function useCardGridNav<T>(opts: {
  items: T[]
  /** True when the detail view is showing (disables grid nav, enables Esc) */
  inDetail: boolean
  onEnter: (item: T, index: number) => void
  onExit: () => void
}) {
  const { items, inDetail, onEnter, onExit } = opts
  const [activeIndex, setActiveIndex] = useState(0)
  const gridRef = useRef<HTMLDivElement>(null)
  const viewMode = usePhotoStore((s) => s.viewMode)
  const selectedPhotos = usePhotoStore((s) => s.selectedPhotos)

  // Clamp active index when the item list shrinks
  useEffect(() => {
    if (items.length > 0 && activeIndex >= items.length) {
      setActiveIndex(items.length - 1)
    }
  }, [items.length, activeIndex])

  // Measure column count from the grid container
  const getColumns = useCallback(() => {
    const el = gridRef.current
    if (!el) return 1
    return getComputedStyle(el).gridTemplateColumns.split(' ').length
  }, [])

  // Scroll the active card into view
  const scrollIntoView = useCallback((index: number) => {
    const el = gridRef.current
    if (!el) return
    const card = el.children[index] as HTMLElement | undefined
    card?.scrollIntoView({ block: 'nearest' })
  }, [])

  useEffect(() => {
    if (items.length === 0) return

    const handleKeyDown = (e: KeyboardEvent) => {
      const target = e.target as HTMLElement | null
      if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return

      // Detail view: Escape or Backspace exits back to card grid, but
      // only when the preview is closed and no photos are selected —
      // otherwise defer to Timeline's own Escape handler.
      if (inDetail) {
        if (e.key === 'Backspace') {
          e.preventDefault()
          onExit()
        } else if (e.key === 'Escape' && viewMode === 'grid' && selectedPhotos.length === 0) {
          e.preventDefault()
          onExit()
        }
        return
      }

      // Card grid navigation
      const cols = getColumns()
      const count = items.length
      let next = activeIndex

      switch (e.key) {
        case 'ArrowRight':
          e.preventDefault()
          next = Math.min(activeIndex + 1, count - 1)
          break
        case 'ArrowLeft':
          e.preventDefault()
          next = Math.max(activeIndex - 1, 0)
          break
        case 'ArrowDown':
          e.preventDefault()
          next = Math.min(activeIndex + cols, count - 1)
          break
        case 'ArrowUp':
          e.preventDefault()
          next = Math.max(activeIndex - cols, 0)
          break
        case 'Enter':
          e.preventDefault()
          if (items[activeIndex]) onEnter(items[activeIndex], activeIndex)
          return
        default:
          return
      }

      if (next !== activeIndex) {
        setActiveIndex(next)
        scrollIntoView(next)
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [items, activeIndex, inDetail, onEnter, onExit, getColumns, scrollIntoView, viewMode, selectedPhotos])

  return { activeIndex, setActiveIndex, gridRef }
}
