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

function BatchUpload({ onGenerate, loading }) {
  const [selectedFiles, setSelectedFiles] = useState([])
  const [patientName, setPatientName] = useState('')
  const [dragActive, setDragActive] = useState(false)

  const handleFileChange = (e) => {
    const files = Array.from(e.target.files)
    addFiles(files)
  }

  const addFiles = (files) => {
    const validFiles = files.filter(file => {
      const ext = file.name.toLowerCase()
      return ext.endsWith('.pdf') || ext.endsWith('.jpg') || 
             ext.endsWith('.jpeg') || ext.endsWith('.png')
    })
    
    setSelectedFiles(prev => [...prev, ...validFiles])
  }

  const removeFile = (index) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index))
  }

  const handleDrag = (e) => {
    e.preventDefault()
    e.stopPropagation()
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true)
    } else if (e.type === 'dragleave') {
      setDragActive(false)
    }
  }

  const handleDrop = (e) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)
    
    const files = Array.from(e.dataTransfer.files)
    addFiles(files)
  }

  const handleSubmit = async () => {
    if (selectedFiles.length === 0) {
      alert('请至少选择一个文件')
      return
    }
    
    if (!patientName.trim()) {
      alert('请输入患者姓名')
      return
    }
    
    await onGenerate(selectedFiles, patientName.trim())
  }

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
  }

  return (
    <div className="bg-white rounded-lg shadow-md p-6">
      <h2 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
        <Upload className="w-5 h-5 mr-2 text-indigo-600" />
        批量上传生成综合报告
      </h2>
      
      <p className="text-sm text-gray-600 mb-4">
        上传多个检测报告（血常规、尿常规、生化检查等），系统将自动识别并生成综合健康报告
      </p>

      {/* 患者姓名输入 */}
      <div className="mb-4">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          <User className="w-4 h-4 inline mr-1" />
          患者姓名 *
        </label>
        <input
          type="text"
          value={patientName}
          onChange={(e) => setPatientName(e.target.value)}
          placeholder="请输入患者姓名"
          className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
          disabled={loading}
        />
      </div>

      {/* 文件上传区域 */}
      <div
        className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
          dragActive
            ? 'border-indigo-500 bg-indigo-50'
            : 'border-gray-300 hover:border-gray-400'
        }`}
        onDragEnter={handleDrag}
        onDragLeave={handleDrag}
        onDragOver={handleDrag}
        onDrop={handleDrop}
      >
        <Upload className="w-12 h-12 mx-auto mb-4 text-gray-400" />
        <p className="text-gray-600 mb-2">
          拖拽文件到此处，或
          <label className="text-indigo-600 hover:text-indigo-700 cursor-pointer ml-1">
            点击选择文件
            <input
              type="file"
              multiple
              accept=".pdf,.jpg,.jpeg,.png"
              onChange={handleFileChange}
              className="hidden"
              disabled={loading}
            />
          </label>
        </p>
        <p className="text-sm text-gray-500">支持 PDF、JPG、PNG 格式，可多选</p>
      </div>

      {/* 已选文件列表 */}
      {selectedFiles.length > 0 && (
        <div className="mt-4">
          <h3 className="text-sm font-medium text-gray-700 mb-2">
            已选择 {selectedFiles.length} 个文件
          </h3>
          <div className="space-y-2 max-h-64 overflow-y-auto">
            {selectedFiles.map((file, index) => (
              <div
                key={index}
                className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
              >
                <div className="flex items-center flex-1 min-w-0">
                  <FileText className="w-5 h-5 text-gray-400 mr-2 flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900 truncate">
                      {file.name}
                    </p>
                    <p className="text-xs text-gray-500">
                      {formatFileSize(file.size)}
                    </p>
                  </div>
                </div>
                <button
                  onClick={() => removeFile(index)}
                  disabled={loading}
                  className="ml-2 text-red-500 hover:text-red-700 disabled:opacity-50"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 生成按钮 */}
      <button
        onClick={handleSubmit}
        disabled={loading || selectedFiles.length === 0 || !patientName.trim()}
        className="w-full mt-6 bg-indigo-600 text-white py-3 px-4 rounded-lg font-medium hover:bg-indigo-700 disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center justify-center space-x-2 transition-colors"
      >
        {loading ? (
          <>
            <Loader className="w-5 h-5 animate-spin" />
            <span>正在生成综合报告...</span>
          </>
        ) : (
          <>
            <FileText className="w-5 h-5" />
            <span>生成综合健康报告</span>
          </>
        )}
      </button>

      {/* 说明 */}
      <div className="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
        <p className="text-xs text-yellow-800">
          <strong>注意：</strong>上传的文件仅用于生成报告，处理完成后会自动删除，不会永久保存在系统中。
        </p>
      </div>
    </div>
  )
}

export default BatchUpload
