import { useEffect, useState, useCallback } from 'react';
import {
  pointsApi,
  type PatientStatistics,
  type ConsultationStatistics,
  type FollowUpStatistics,
  type PointsStatistics,
  type HealthDataStats,
  type DialysisStatistics,
} from '../../../api/health/points';
import { doctorApi } from '../../../api/health/doctors';

// 全局缓存：多组件实例共享数据，避免重复请求
let cachedStats: Record<string, unknown> | null = null;
let cachedAt = 0;
const CACHE_TTL = 5 * 60 * 1000; // 5 分钟
let fetchPromise: Promise<Record<string, unknown>> | null = null;

export interface StatsData {
  patientStats: PatientStatistics | null;
  consultationStats: ConsultationStatistics | null;
  followUpStats: FollowUpStatistics | null;
  pointsStats: PointsStatistics | null;
  healthDataStats: HealthDataStats | null;
  dialysisStats: DialysisStatistics | null;
  doctorCount: number;
  loading: boolean;
  error: string | null;
  refresh: () => void;
}

export function useStatsData(): StatsData {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [patientStats, setPatientStats] = useState<PatientStatistics | null>(null);
  const [consultationStats, setConsultationStats] = useState<ConsultationStatistics | null>(null);
  const [followUpStats, setFollowUpStats] = useState<FollowUpStatistics | null>(null);
  const [pointsStats, setPointsStats] = useState<PointsStatistics | null>(null);
  const [healthDataStats, setHealthDataStats] = useState<HealthDataStats | null>(null);
  const [dialysisStats, setDialysisStats] = useState<DialysisStatistics | null>(null);
  const [doctorCount, setDoctorCount] = useState(0);

  const fetchAllStats = useCallback(async () => {
    // 缓存未过期，直接使用
    if (cachedStats && Date.now() - cachedAt < CACHE_TTL) {
      const c = cachedStats;
      setPatientStats(c.patientStats as PatientStatistics | null);
      setConsultationStats(c.consultationStats as ConsultationStatistics | null);
      setFollowUpStats(c.followUpStats as FollowUpStatistics | null);
      setPointsStats(c.pointsStats as PointsStatistics | null);
      setHealthDataStats(c.healthDataStats as HealthDataStats | null);
      setDialysisStats(c.dialysisStats as DialysisStatistics | null);
      setDoctorCount(c.doctorCount as number);
      setLoading(false);
      return;
    }

    // 已有正在进行的请求，等待它完成
    if (fetchPromise) {
      const c = await fetchPromise;
      setPatientStats(c.patientStats as PatientStatistics | null);
      setConsultationStats(c.consultationStats as ConsultationStatistics | null);
      setFollowUpStats(c.followUpStats as FollowUpStatistics | null);
      setPointsStats(c.pointsStats as PointsStatistics | null);
      setHealthDataStats(c.healthDataStats as HealthDataStats | null);
      setDialysisStats(c.dialysisStats as DialysisStatistics | null);
      setDoctorCount(c.doctorCount as number);
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(null);

    // 创建新请求
    fetchPromise = (async () => {
      let hasAnyError = false;
      const errors: string[] = [];

      const results: Record<string, unknown> = {
        patientStats: null,
        consultationStats: null,
        followUpStats: null,
        pointsStats: null,
        healthDataStats: null,
        dialysisStats: null,
        doctorCount: 0,
      };

      const tryFetch = async <T,>(fn: () => Promise<T>, key: string, label: string) => {
        try {
          const data = await fn();
          results[key] = data;
        } catch {
          hasAnyError = true;
          errors.push(label);
        }
      };

      await Promise.all([
        tryFetch(() => pointsApi.getPatientStats({ silent: true }), 'patientStats', '患者'),
        tryFetch(() => pointsApi.getConsultationStats({ silent: true }), 'consultationStats', '咨询'),
        tryFetch(() => pointsApi.getFollowUpStats({ silent: true }), 'followUpStats', '随访'),
        tryFetch(() => pointsApi.getStatistics({ silent: true }), 'pointsStats', '积分'),
        tryFetch(() => pointsApi.getHealthDataStats({ silent: true }), 'healthDataStats', '健康数据'),
        tryFetch(() => pointsApi.getDialysisStats({ silent: true }), 'dialysisStats', '透析'),
        tryFetch(
          async () => { const r = await doctorApi.list({ page: 1, page_size: 1 }); return r.total; },
          'doctorCount',
          '医护',
        ),
      ]);

      if (!hasAnyError || errors.length < 7) {
        cachedStats = results;
        cachedAt = Date.now();
      }

      if (hasAnyError && errors.length === 7) {
        setError('加载统计数据失败');
      }

      return results;
    })();

    try {
      const c = await fetchPromise;
      setPatientStats(c.patientStats as PatientStatistics | null);
      setConsultationStats(c.consultationStats as ConsultationStatistics | null);
      setFollowUpStats(c.followUpStats as FollowUpStatistics | null);
      setPointsStats(c.pointsStats as PointsStatistics | null);
      setHealthDataStats(c.healthDataStats as HealthDataStats | null);
      setDialysisStats(c.dialysisStats as DialysisStatistics | null);
      setDoctorCount(c.doctorCount as number);
    } finally {
      fetchPromise = null;
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchAllStats();
  }, [fetchAllStats]);

  return {
    patientStats, consultationStats, followUpStats, pointsStats, healthDataStats, dialysisStats, doctorCount,
    loading, error, refresh: fetchAllStats,
  };
}
