import React, { useState, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { getReportDetail, LabReport } from '../../../services/report';
import Loading from '../../../components/Loading';
import './index.scss';

interface IndicatorItem {
  name: string;
  value: number;
  unit?: string;
  reference_min?: number;
  reference_max?: number;
  status?: string;
}

export default function ReportDetail() {
  const router = useRouter();
  const id = router.params.id || '';
  const patientId = Taro.getStorageSync('current_patient_id') || '';

  const [report, setReport] = useState<LabReport | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!id || !patientId) return;
    setLoading(true);
    getReportDetail(patientId, id)
      .then((data) => setReport(data))
      .catch(() => Taro.showToast({ title: '加载失败', icon: 'none' }))
      .finally(() => setLoading(false));
  }, [id, patientId]);

  const indicators: IndicatorItem[] = React.useMemo(() => {
    if (!report?.indicators || typeof report.indicators !== 'object') return [];
    return Object.entries(report.indicators).map(([name, val]) => ({
      name,
      value: val.value,
      unit: val.unit,
      reference_min: val.reference_min,
      reference_max: val.reference_max,
      status: val.status,
    }));
  }, [report]);

  const getStatusInfo = (status?: string) => {
    if (status === 'high') return { text: '偏高', icon: '', className: 'high' };
    if (status === 'low') return { text: '偏低', icon: '', className: 'low' };
    return { text: '正常', icon: '', className: 'normal' };
  };

  if (loading) {
    return (
      <View className='detail-page'>
        <Loading />
      </View>
    );
  }

  if (!report) {
    return (
      <View className='detail-page'>
        <View className='empty-state'>
          <Text className='empty-text'>报告不存在</Text>
        </View>
      </View>
    );
  }

  return (
    <View className='detail-page'>
      {/* 基本信息 */}
      <View className='detail-card'>
        <Text className='detail-title'>{report.report_type}</Text>
        <View className='detail-row'>
          <Text className='detail-label'>报告日期</Text>
          <Text className='detail-value'>{report.report_date}</Text>
        </View>
        {report.doctor_interpretation && (
          <View className='detail-row'>
            <Text className='detail-label'>医生解读</Text>
            <Text className='detail-value'>{report.doctor_interpretation}</Text>
          </View>
        )}
      </View>

      {/* 指标列表 */}
      <View className='indicators-card'>
        <Text className='section-title'>检查指标</Text>
        {indicators.map((item) => {
          const statusInfo = getStatusInfo(item.status);
          return (
            <View className='indicator-item' key={item.name}>
              <View className='indicator-left'>
                <Text className='indicator-name'>{item.name}</Text>
                <Text className='indicator-value'>
                  {item.value}
                  {item.unit ? ` ${item.unit}` : ''}
                </Text>
              </View>
              <View className='indicator-right'>
                {item.reference_min != null && item.reference_max != null && (
                  <Text className='indicator-ref'>
                    {item.reference_min}~{item.reference_max}
                  </Text>
                )}
                <Text className={`indicator-status ${statusInfo.className}`}>
                  {statusInfo.icon} {statusInfo.text}
                </Text>
              </View>
            </View>
          );
        })}
      </View>
    </View>
  );
}
