import { useCallback, useRef } from 'react'

interface UseLongPressOptions {
  onLongPress: (cellId: string) => void
  onLongPressEnd: () => void
  delay?: number
}

/**
 * 自定义长按 Hook
 * 支持触摸、鼠标和键盘（空格键）
 */
export function useLongPress(
  cellId: string,
  { onLongPress, onLongPressEnd, delay = 600 }: UseLongPressOptions
) {
  const timerRef = useRef<number>()
  const isLongPressRef = useRef(false)

  const start = useCallback(() => {
    isLongPressRef.current = false
    timerRef.current = window.setTimeout(() => {
      isLongPressRef.current = true
      onLongPress(cellId)
    }, delay)
  }, [cellId, onLongPress, delay])

  const cancel = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current)
    }
    // 只有在长按成功触发后才调用 onLongPressEnd
    if (isLongPressRef.current) {
      onLongPressEnd()
    }
    isLongPressRef.current = false
  }, [onLongPressEnd])

  return {
    onPointerDown: start,
    onPointerUp: cancel,
    onPointerLeave: cancel,
    onPointerCancel: cancel,
    onContextMenu: (e: React.MouseEvent) => {
      e.preventDefault()
      cancel()
    },
    // 键盘支持（空格键长按）
    onKeyDown: (e: React.KeyboardEvent) => {
      if (e.key === ' ' && !e.repeat) {
        e.preventDefault()
        start()
      }
    },
    onKeyUp: (e: React.KeyboardEvent) => {
      if (e.key === ' ') {
        e.preventDefault()
        cancel()
      }
    },
  }
}
