"use client"

import { useCallback } from "react"
import type { DriveFileInfo } from "@/lib/api/types"
import { applyDriveDragPreview, removeDriveDragPreview } from "@/lib/drive/drive-drag-preview"
import { resolveDragSources, setDriveDragData } from "@/lib/drive/drive-dnd"
import { isFromDriveMenu } from "@/lib/drive/drive-menu-guard"
import { useDriveUIStore } from "@/lib/stores/drive-ui-store"

export function useDriveDragSource({
  file,
  allItems,
  disabled,
}: {
  file: DriveFileInfo
  allItems: DriveFileInfo[]
  disabled?: boolean
}) {
  const selectedPaths = useDriveUIStore((s) => s.selectedPaths)
  const setDraggingItems = useDriveUIStore((s) => s.setDraggingItems)

  const onDragStart = useCallback(
    (event: React.DragEvent) => {
      if (disabled || isFromDriveMenu(event.target)) {
        event.preventDefault()
        return
      }
      const sources = resolveDragSources(file, selectedPaths, allItems)
      const previewFiles = sources
        .map((s) => allItems.find((i) => i.path === s.path))
        .filter((f): f is DriveFileInfo => Boolean(f))
      setDriveDragData(event.dataTransfer, sources)
      applyDriveDragPreview(
        event.dataTransfer,
        previewFiles.length > 0 ? previewFiles : [file],
        event.currentTarget as HTMLElement
      )
      setDraggingItems(sources)
    },
    [allItems, disabled, file, selectedPaths, setDraggingItems]
  )

  const onDragEnd = useCallback(() => {
    removeDriveDragPreview()
    setDraggingItems(null)
  }, [setDraggingItems])

  if (disabled) {
    return { dragProps: {} as const }
  }

  return {
    dragProps: {
      draggable: true,
      onDragStart,
      onDragEnd,
    } as const,
  }
}
