import React, { useState, useEffect } from 'react'
import { UploadCloud } from '../Icons'

export const DropOverlay = React.memo(function DropOverlay() {
  const [dragCounter, setDragCounter] = useState(0)

  useEffect(() => {
    const handleDragEnter = (e: DragEvent) => {
      e.preventDefault()
      setDragCounter(prev => prev + 1)
    }
    const handleDragLeave = (e: DragEvent) => {
      e.preventDefault()
      setDragCounter(prev => Math.max(0, prev - 1))
    }
    const handleDragOver = (e: DragEvent) => {
      e.preventDefault()
    }
    const handleDrop = () => {
      setDragCounter(0)
    }

    document.addEventListener('dragenter', handleDragEnter)
    document.addEventListener('dragleave', handleDragLeave)
    document.addEventListener('dragover', handleDragOver)
    document.addEventListener('drop', handleDrop)

    return () => {
      document.removeEventListener('dragenter', handleDragEnter)
      document.removeEventListener('dragleave', handleDragLeave)
      document.removeEventListener('dragover', handleDragOver)
      document.removeEventListener('drop', handleDrop)
    }
  }, [])

  if (dragCounter <= 0) return null

  return (
    <div id="drop-overlay" role="dialog" aria-label="拖拽文件以打开">
      <div className="drop-content">
        <UploadCloud size={64} />
        <p>释放文件以打开</p>
      </div>
    </div>
  )
})

DropOverlay.displayName = 'DropOverlay'
