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

interface DragState {
  dragging: boolean
  dragIndex: number
  dropIndex: number
  startX: number
  startY: number
}

/**
 * 拖拽排序 composable
 * 支持 uniapp app 和小程序
 */
export function useDragSort<T>(items: Ref<T[]>, onUpdate: (newItems: T[]) => void) {
  const dragState = ref<DragState>({
    dragging: false,
    dragIndex: -1,
    dropIndex: -1,
    startX: 0,
    startY: 0,
  })

  // 开始拖拽
  function handleTouchStart(e: any, index: number) {
    const touch = e.touches[0] || e.changedTouches[0]
    dragState.value = {
      dragging: true,
      dragIndex: index,
      dropIndex: index,
      startX: touch.clientX || touch.pageX,
      startY: touch.clientY || touch.pageY,
    }
  }

  // 拖拽中
  function handleTouchMove(e: any) {
    if (!dragState.value.dragging)
      return

    const touch = e.touches[0] || e.changedTouches[0]
    const currentX = touch.clientX || touch.pageX
    const currentY = touch.clientY || touch.pageY

    // 计算移动距离
    const deltaX = currentX - dragState.value.startX
    const deltaY = currentY - dragState.value.startY

    // 这里可以添加更多的拖拽逻辑，比如实时更新位置
    // 但为了简单，我们在 touchend 时处理排序
  }

  // 结束拖拽
  function handleTouchEnd(e: any, index: number) {
    if (!dragState.value.dragging)
      return

    const dragIndex = dragState.value.dragIndex
    const dropIndex = index

    if (dragIndex !== dropIndex && dragIndex !== -1) {
      // 重新排序
      const newItems = [...items.value]
      const [removed] = newItems.splice(dragIndex, 1)
      newItems.splice(dropIndex, 0, removed)
      onUpdate(newItems)
    }

    dragState.value = {
      dragging: false,
      dragIndex: -1,
      dropIndex: -1,
      startX: 0,
      startY: 0,
    }
  }

  // 长按开始拖拽
  function handleLongPress(index: number) {
    return {
      onTouchstart: (e: any) => handleTouchStart(e, index),
      onTouchmove: handleTouchMove,
      onTouchend: (e: any) => handleTouchEnd(e, index),
    }
  }

  return {
    dragState,
    handleTouchStart,
    handleTouchMove,
    handleTouchEnd,
    handleLongPress,
  }
}
