import { ref, type Ref } from 'vue'

export function useImageDropUpload(options: {
  disabled?: Ref<boolean> | (() => boolean)
  onFiles: (files: File[]) => void
  acceptImagesOnly?: boolean
}) {
  const isDragging = ref(false)

  const isDisabled = () => {
    if (typeof options.disabled === 'function') return options.disabled()
    return options.disabled?.value ?? false
  }

  const handleDragOver = (e: DragEvent) => {
    if (isDisabled()) return
    e.preventDefault()
    isDragging.value = true
  }

  const handleDragEnter = (e: DragEvent) => {
    if (isDisabled()) return
    e.preventDefault()
    isDragging.value = true
  }

  const handleDragLeave = (e: DragEvent) => {
    if (isDisabled()) return
    e.preventDefault()
    isDragging.value = false
  }

  const handleDrop = (e: DragEvent) => {
    if (isDisabled()) return
    e.preventDefault()
    isDragging.value = false

    if (!e.dataTransfer?.files?.length) return

    let files = Array.from(e.dataTransfer.files)
    if (options.acceptImagesOnly !== false) {
      files = files.filter(file => file.type.startsWith('image/'))
    }
    if (files.length > 0) {
      options.onFiles(files)
    }
  }

  return {
    isDragging,
    handleDragOver,
    handleDragEnter,
    handleDragLeave,
    handleDrop,
  }
}
