import React, { useState } from 'react'
import { X, FileText, AlertTriangle, CheckCircle, Activity, Download } from 'lucide-react'

function ReportDetail({ report, onClose, onGeneratePDF }) {
  const [generatingPDF, setGeneratingPDF] = useState(false)

  const handleGeneratePDF = async () => {
    setGeneratingPDF(true)
    try {
      await onGeneratePDF(report.id)
    } finally {
      setGeneratingPDF(false)
    }
  }
  const analysis = report.analysis || {}

  // 兼容不同结构的返回结果
  const keyFindings = Array.isArray(analysis.key_findings)
    ? analysis.key_findings.map((item) =>
        typeof item === 'string'
          ? item
          : item?.finding || item?.text || JSON.stringify(item)
      )
    : []

  const abnormalItems = Array.isArray(analysis.abnormal_items)
    ? analysis.abnormal_items
    : []

  let riskAssessmentText = ''
  if (typeof analysis.risk_assessment === 'string') {
    riskAssessmentText = analysis.risk_assessment
  } else if (analysis.risk_assessment && typeof analysis.risk_assessment === 'object') {
    const ra = analysis.risk_assessment
    const parts = []
    if (Array.isArray(ra.high_risk) && ra.high_risk.length > 0) {
      parts.push(`【高风险】${ra.high_risk.join('；')}`)
    }
    if (Array.isArray(ra.medium_risk) && ra.medium_risk.length > 0) {
      parts.push(`【中风险】${ra.medium_risk.join('；')}`)
    }
    if (Array.isArray(ra.low_risk) && ra.low_risk.length > 0) {
      parts.push(`【低风险】${ra.low_risk.join('；')}`)
    }
    riskAssessmentText = parts.join('\n')
  }

  const recommendations = Array.isArray(analysis.recommendations)
    ? analysis.recommendations.map((item) =>
        typeof item === 'string'
          ? item
          : item?.recommendation || item?.text || JSON.stringify(item)
      )
    : []

  return (
    <div className="bg-white rounded-lg shadow-md">
      {/* Header */}
      <div className="border-b border-gray-200 p-6 flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 flex items-center">
            <FileText className="w-6 h-6 mr-2 text-indigo-600" />
            报告详情
          </h2>
          <p className="text-sm text-gray-600 mt-1">{report.filename}</p>
        </div>
        <div className="flex items-center space-x-3">
          <button
            onClick={handleGeneratePDF}
            disabled={generatingPDF}
            className="flex items-center space-x-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
          >
            <Download className="w-4 h-4" />
            <span>{generatingPDF ? '生成中...' : '生成PDF报告'}</span>
          </button>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="p-6 space-y-6 max-h-[calc(100vh-300px)] overflow-y-auto">
        {/* Summary */}
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <h3 className="font-semibold text-blue-900 mb-2 flex items-center">
            <Activity className="w-5 h-5 mr-2" />
            摘要
          </h3>
          <p className="text-blue-800">{analysis.summary || '暂无摘要'}</p>
        </div>

        {/* Key Findings */}
        {keyFindings.length > 0 && (
          <div>
            <h3 className="font-semibold text-gray-900 mb-3 flex items-center">
              <CheckCircle className="w-5 h-5 mr-2 text-green-600" />
              关键发现
            </h3>
            <ul className="space-y-2">
              {keyFindings.map((finding, index) => (
                <li key={index} className="flex items-start">
                  <span className="inline-block w-2 h-2 bg-green-500 rounded-full mt-2 mr-3 flex-shrink-0"></span>
                  <span className="text-gray-700">{finding}</span>
                </li>
              ))}
            </ul>
          </div>
        )}

        {/* Abnormal Items */}
        {abnormalItems.length > 0 && (
          <div>
            <h3 className="font-semibold text-gray-900 mb-3 flex items-center">
              <AlertTriangle className="w-5 h-5 mr-2 text-red-600" />
              异常指标
            </h3>
            <div className="space-y-3">
              {abnormalItems.map((item, index) => (
                <div key={index} className="bg-red-50 border border-red-200 rounded-lg p-3">
                  <p className="font-medium text-red-900">{item.name || item}</p>
                  {item.value && (
                    <p className="text-sm text-red-700 mt-1">
                      测量值: {item.value} {item.reference && `(参考: ${item.reference})`}
                    </p>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Risk Assessment */}
        {riskAssessmentText && (
          <div>
            <h3 className="font-semibold text-gray-900 mb-3">风险评估</h3>
            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
              <p className="text-yellow-900 whitespace-pre-wrap">{riskAssessmentText}</p>
            </div>
          </div>
        )}

        {/* Recommendations */}
        {recommendations.length > 0 && (
          <div>
            <h3 className="font-semibold text-gray-900 mb-3">建议</h3>
            <ul className="space-y-2">
              {recommendations.map((rec, index) => (
                <li key={index} className="flex items-start">
                  <span className="inline-block w-2 h-2 bg-indigo-500 rounded-full mt-2 mr-3 flex-shrink-0"></span>
                  <span className="text-gray-700">{rec}</span>
                </li>
              ))}
            </ul>
          </div>
        )}

        {/* OCR Text */}
        {report.ocr_text && (
          <div>
            <h3 className="font-semibold text-gray-900 mb-3">原始文本</h3>
            <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
              <pre className="text-sm text-gray-700 whitespace-pre-wrap font-mono">
                {report.ocr_text}
              </pre>
            </div>
          </div>
        )}

        {/* Note */}
        {analysis.note && (
          <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
            <p className="text-xs text-gray-600 italic">{analysis.note}</p>
          </div>
        )}
      </div>
    </div>
  )
}

export default ReportDetail
