import { useRef, useCallback, useEffect } from 'react'

interface UseDragScrollOptions {
  scrollMultiplier?: number
}

export function useDragScroll(options: UseDragScrollOptions = {}) {
  const { scrollMultiplier = 1.5 } = options
  const scrollRef = useRef<HTMLDivElement>(null)
  const isDragging = useRef(false)
  const startX = useRef(0)
  const scrollLeft = useRef(0)

  const handleMouseDown = useCallback(
    (e: React.MouseEvent) => {
      if (!scrollRef.current || window.innerWidth >= 800) return
      isDragging.current = true
      startX.current = e.pageX - scrollRef.current.offsetLeft
      scrollLeft.current = scrollRef.current.scrollLeft
      scrollRef.current.style.cursor = 'grabbing'
    },
    []
  )

  const handleMouseUp = useCallback(() => {
    isDragging.current = false
    if (scrollRef.current) scrollRef.current.style.cursor = 'grab'
  }, [])

  const handleMouseMove = useCallback(
    (e: React.MouseEvent) => {
      if (!isDragging.current || !scrollRef.current) return
      e.preventDefault()
      const x = e.pageX - scrollRef.current.offsetLeft
      const walk = (x - startX.current) * scrollMultiplier
      scrollRef.current.scrollLeft = scrollLeft.current - walk
    },
    [scrollMultiplier]
  )

  const touchStartX = useRef(0)
  const touchScrollLeft = useRef(0)

  const handleTouchStart = useCallback((e: React.TouchEvent) => {
    if (!scrollRef.current) return
    touchStartX.current = e.touches[0].pageX
    touchScrollLeft.current = scrollRef.current.scrollLeft
  }, [])

  const handleTouchMove = useCallback(
    (e: React.TouchEvent) => {
      if (!scrollRef.current) return
      const x = e.touches[0].pageX
      const walk = (x - touchStartX.current) * scrollMultiplier
      scrollRef.current.scrollLeft = touchScrollLeft.current - walk
    },
    [scrollMultiplier]
  )

  useEffect(() => {
    const handleGlobalMouseUp = () => {
      isDragging.current = false
      if (scrollRef.current && window.innerWidth < 800) scrollRef.current.style.cursor = 'grab'
    }
    window.addEventListener('mouseup', handleGlobalMouseUp)
    return () => window.removeEventListener('mouseup', handleGlobalMouseUp)
  }, [])

  return {
    scrollRef,
    isDragging,
    handlers: {
      onMouseDown: handleMouseDown,
      onMouseUp: handleMouseUp,
      onMouseMove: handleMouseMove,
      onMouseLeave: handleMouseUp,
      onTouchStart: handleTouchStart,
      onTouchMove: handleTouchMove,
    },
  }
}