import React, { useState } from 'react'
import { Upload, Loader } from 'lucide-react'

function FileUpload({ onUpload, loading }) {
  const [dragging, setDragging] = useState(false)

  const handleDragOver = (e) => {
    e.preventDefault()
    setDragging(true)
  }

  const handleDragLeave = () => {
    setDragging(false)
  }

  const handleDrop = (e) => {
    e.preventDefault()
    setDragging(false)
    const files = Array.from(e.dataTransfer.files)
    if (files.length > 0) {
      handleFileSelect(files[0])
    }
  }

  const handleFileSelect = async (file) => {
    if (!file) return

    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf']
    if (!allowedTypes.includes(file.type)) {
      alert('不支持的文件格式，请上传 JPG、PNG 或 PDF 文件')
      return
    }

    try {
      await onUpload(file)
    } catch (err) {
      console.error('Upload failed:', err)
    }
  }

  return (
    <div className="bg-white rounded-lg shadow-md p-6">
      <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center">
        <Upload className="w-5 h-5 mr-2 text-indigo-600" />
        上传医疗报告
      </h2>
      
      <div
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
          dragging
            ? 'border-indigo-500 bg-indigo-50'
            : 'border-gray-300 hover:border-indigo-400'
        }`}
      >
        {loading ? (
          <div className="flex flex-col items-center">
            <Loader className="w-8 h-8 text-indigo-600 animate-spin mb-2" />
            <p className="text-gray-600">上传中...</p>
          </div>
        ) : (
          <>
            <Upload className="w-12 h-12 text-gray-400 mx-auto mb-3" />
            <p className="text-gray-700 mb-2">拖拽文件到此处或点击上传</p>
            <p className="text-sm text-gray-500 mb-4">支持 JPG、PNG、PDF 格式</p>
            <label className="inline-block">
              <input
                type="file"
                className="hidden"
                accept=".jpg,.jpeg,.png,.pdf"
                onChange={(e) => {
                  if (e.target.files[0]) {
                    handleFileSelect(e.target.files[0])
                  }
                }}
                disabled={loading}
              />
              <span className="px-4 py-2 bg-indigo-600 text-white rounded-lg cursor-pointer hover:bg-indigo-700 transition-colors">
                选择文件
              </span>
            </label>
          </>
        )}
      </div>
    </div>
  )
}

export default FileUpload
