import React, { useState, useEffect } from 'react'
import { FileText, Search, Brain, Check, AlertCircle, Trash2, Layers } from 'lucide-react'
import FileUpload from './components/FileUpload'
import ReportList from './components/ReportList'
import ReportDetail from './components/ReportDetail'
import IntegrationResult from './components/IntegrationResult'
import BatchUpload from './components/BatchUpload'
import { api } from './services/api'

function App() {
  const [reports, setReports] = useState([])
  const [selectedReport, setSelectedReport] = useState(null)
  const [integrationResult, setIntegrationResult] = useState(null)
  const [selectedReports, setSelectedReports] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)
  const [activeTab, setActiveTab] = useState('batch') // 默认使用批量模式

  const loadReports = async () => {
    try {
      const data = await api.getReports()
      setReports(data.reports || [])
    } catch (err) {
      setError('加载报告列表失败')
    }
  }

  const handleFileUpload = async (file) => {
    try {
      setLoading(true)
      setError(null)
      const result = await api.uploadFile(file)
      await loadReports()
      return result
    } catch (err) {
      setError('文件上传失败: ' + err.message)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const handleOCR = async (fileId) => {
    try {
      setLoading(true)
      setError(null)
      await api.performOCR(fileId)
      await loadReports()
    } catch (err) {
      setError('OCR识别失败: ' + err.message)
    } finally {
      setLoading(false)
    }
  }

  const handleAnalyze = async (fileId) => {
    try {
      setLoading(true)
      setError(null)
      await api.analyzeReport(fileId)
      await loadReports()
      const detail = await api.getReportDetail(fileId)
      setSelectedReport(detail.report)
    } catch (err) {
      setError('报告分析失败: ' + err.message)
    } finally {
      setLoading(false)
    }
  }

  const handleIntegrate = async () => {
    if (selectedReports.length === 0) {
      setError('请至少选择一份报告进行整合')
      return
    }

    try {
      setLoading(true)
      setError(null)
      const result = await api.integrateReports(selectedReports)
      setIntegrationResult(result)
    } catch (err) {
      setError('报告整合失败: ' + err.message)
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (fileId) => {
    if (!confirm('确定要删除这份报告吗？')) return

    try {
      setLoading(true)
      await api.deleteReport(fileId)
      await loadReports()
      if (selectedReport?.id === fileId) {
        setSelectedReport(null)
      }
      setSelectedReports(prev => prev.filter(id => id !== fileId))
    } catch (err) {
      setError('删除失败: ' + err.message)
    } finally {
      setLoading(false)
    }
  }

  const toggleReportSelection = (reportId) => {
    setSelectedReports(prev => 
      prev.includes(reportId) 
        ? prev.filter(id => id !== reportId)
        : [...prev, reportId]
    )
  }

  const viewReportDetail = async (reportId) => {
    try {
      const detail = await api.getReportDetail(reportId)
      setSelectedReport(detail.report)
      setIntegrationResult(null)
    } catch (err) {
      setError('加载报告详情失败')
    }
  }

  const handleGeneratePDF = async (fileId) => {
    try {
      setLoading(true)
      setError(null)
      const result = await api.generatePDF(fileId)
      // 生成成功后直接下载
      api.downloadPDF(fileId)
      // 显示成功提示
      alert('PDF报告生成成功！')
    } catch (err) {
      setError('PDF生成失败: ' + err.message)
    } finally {
      setLoading(false)
    }
  }

  const handleBatchGenerate = async (files, patientName) => {
    try {
      setLoading(true)
      setError(null)
      const result = await api.generateComprehensiveReport(files, patientName)
      // 生成成功后直接下载
      api.downloadComprehensiveReport(result.pdf_filename)
      // 显示成功提示
      alert(`综合健康报告生成成功！\n患者：${result.patient_name}\n报告数量：${result.report_count} 份`)
    } catch (err) {
      setError('综合报告生成失败: ' + err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
      {/* Header */}
      <header className="bg-white shadow-md">
        <div className="max-w-7xl mx-auto px-4 py-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <FileText className="w-8 h-8 text-indigo-600" />
              <h1 className="text-3xl font-bold text-gray-900">医疗报告分析系统</h1>
            </div>
            <div className="flex items-center space-x-2 text-sm text-gray-600">
              <div className="flex items-center space-x-1">
                <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                <span>系统运行中</span>
              </div>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 py-8">
        {/* Error Alert */}
        {error && (
          <div className="mb-4 bg-red-50 border border-red-200 rounded-lg p-4 flex items-start">
            <AlertCircle className="w-5 h-5 text-red-500 mt-0.5 mr-3" />
            <div>
              <p className="text-red-800 font-medium">错误</p>
              <p className="text-red-700 text-sm">{error}</p>
            </div>
            <button onClick={() => setError(null)} className="ml-auto text-red-500 hover:text-red-700">
              ×
            </button>
          </div>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Left Panel - Upload & Reports */}
          <div className="lg:col-span-1 space-y-6">
            {/* 选项卡切换 */}
            <div className="bg-white rounded-lg shadow-md p-2 flex space-x-2">
              <button
                className="flex-1 py-2 px-4 rounded-md font-medium bg-indigo-600 text-white cursor-default"
              >
                <Layers className="w-4 h-4 inline mr-2" />
                批量生成
              </button>
            </div>

            {/* File Upload */}
            <BatchUpload onGenerate={handleBatchGenerate} loading={loading} />

            {/* Reports List - 只在单个上传模式显示 */}
            {false && activeTab === 'single' && (
              <ReportList
              reports={reports}
              selectedReports={selectedReports}
              onToggleSelect={toggleReportSelection}
              onView={viewReportDetail}
              onOCR={handleOCR}
              onAnalyze={handleAnalyze}
              onDelete={handleDelete}
              loading={loading}
              />
            )}

            {/* Integration Button */}
            {false && reports.length > 0 && (
              <div className="bg-white rounded-lg shadow-md p-4">
                <button
                  onClick={handleIntegrate}
                  disabled={loading || selectedReports.length === 0}
                  className="w-full bg-indigo-600 text-white py-3 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"
                >
                  <Brain className="w-5 h-5" />
                  <span>整合分析 ({selectedReports.length}份)</span>
                </button>
              </div>
            )}
          </div>

          {/* Right Panel - Details */}
          <div className="lg:col-span-2">
            {integrationResult ? (
              <IntegrationResult result={integrationResult} onClose={() => setIntegrationResult(null)} />
            ) : selectedReport ? (
              <ReportDetail 
                report={selectedReport} 
                onClose={() => setSelectedReport(null)}
                onGeneratePDF={handleGeneratePDF}
              />
            ) : (
              <div className="bg-white rounded-lg shadow-md p-12 text-center">
                <Brain className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <p className="text-gray-500 text-lg">上传医疗报告开始分析</p>
                <p className="text-gray-400 text-sm mt-2">支持 JPG、PNG、PDF 格式</p>
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  )
}

export default App
