import React, { useState, useCallback } from 'react';
import { View, Text } from '@tarojs/components';
import Taro, { useDidShow, usePullDownRefresh, useReachBottom } from '@tarojs/taro';
import { listReports, LabReport } from '../../../services/report';
import './index.scss';

const PAGE_SIZE = 20;

export default function MyReports() {
  const [reports, setReports] = useState<LabReport[]>([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  const patientId = Taro.getStorageSync('current_patient_id') || '';

  const fetchData = useCallback(async (p: number, append = false) => {
    if (!patientId) return;
    setLoading(true);
    try {
      const res = await listReports(patientId, p);
      const list = res.data || [];
      setReports(append ? (prev) => [...prev, ...list] : list);
      setTotal(res.total);
      setPage(p);
    } catch {
      Taro.showToast({ title: '加载失败', icon: 'none' });
    } finally {
      setLoading(false);
    }
  }, [patientId]);

  useDidShow(() => {
    fetchData(1);
  }, [fetchData]);

  usePullDownRefresh(() => {
    fetchData(1).finally(() => {
      Taro.stopPullDownRefresh();
    });
  });

  useReachBottom(() => {
    if (!loading && reports.length < total) {
      fetchData(page + 1, true);
    }
  });

  const goToDetail = (id: string) => {
    Taro.navigateTo({ url: `/pages/report/detail/index?id=${id}` });
  };

  const formatStatus = (report: LabReport) => {
    const indicators = report.indicators;
    if (!indicators || typeof indicators !== 'object') return '未知';
    const vals = Object.values(indicators) as Array<{ status?: string }>;
    const hasAbnormal = vals.some((v) => v.status === 'high' || v.status === 'low');
    return hasAbnormal ? '异常' : '正常';
  };

  return (
    <View className='my-reports-page'>
      <View className='report-list'>
        {reports.map((r) => (
          <View
            className='report-card'
            key={r.id}
            onClick={() => goToDetail(r.id)}
          >
            <View className='report-card-top'>
              <Text className='report-type'>{r.report_type}</Text>
              <Text className={`report-status ${formatStatus(r) === '正常' ? 'normal' : 'abnormal'}`}>
                {formatStatus(r)}
              </Text>
            </View>
            <Text className='report-date'>{r.report_date}</Text>
          </View>
        ))}
      </View>

      {reports.length === 0 && !loading && (
        <View className='empty-state'>
          <Text className='empty-text'>暂无报告记录</Text>
        </View>
      )}

      {loading && (
        <View className='loading-hint'>
          <Text className='loading-text'>加载中...</Text>
        </View>
      )}
    </View>
  );
}
