import { ref, onUnmounted, type Ref } from 'vue'

interface UseDraggableOptions {
  onDragStart?: () => void
  onDragEnd?: () => void
}

export function useDraggable(targetRef: Ref<HTMLElement | undefined>, options?: UseDraggableOptions) {
  const isDragging = ref(false)
  const startX = ref(0)
  const startY = ref(0)
  const startLeft = ref(0)
  const startTop = ref(0)

  const handleMouseDown = (e: MouseEvent) => {
    // 只允许左键拖拽
    if (e.button !== 0) return

    isDragging.value = true
    startX.value = e.clientX
    startY.value = e.clientY

    if (targetRef.value) {
      const rect = targetRef.value.getBoundingClientRect()
      startLeft.value = rect.left
      startTop.value = rect.top
    }

    options?.onDragStart?.()

    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)
  }

  const handleMouseMove = (e: MouseEvent) => {
    if (!isDragging.value || !targetRef.value) return

    const deltaX = e.clientX - startX.value
    const deltaY = e.clientY - startY.value

    targetRef.value.style.left = `${startLeft.value + deltaX}px`
    targetRef.value.style.top = `${startTop.value + deltaY}px`
  }

  const handleMouseUp = () => {
    isDragging.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    options?.onDragEnd?.()
  }

  onUnmounted(() => {
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  })

  return {
    isDragging,
    handleMouseDown
  }
}
