import { useState, useCallback } from 'react';
import { useAlertSSE, type VitalUpdateSSEEvent } from './useAlertSSE';

export type VitalUpdateEvent = VitalUpdateSSEEvent;

interface PatientVital {
  patient_id: string;
  device_type: string;
  latest_value?: number;
  updated_at: string;
}

interface UseVitalSSEOptions {
  enabled?: boolean;
  patientIds?: string[];
  onUpdate?: (data: VitalUpdateEvent) => void;
}

interface UseVitalSSEReturn {
  connected: boolean;
  patientVitals: Map<string, PatientVital>;
  lastUpdate: VitalUpdateEvent | null;
}

/**
 * 实时体征 hook — 复用全局 SSE 连接的 vital_update 事件。
 *
 * 内部调用 useAlertSSE（共享 /messages/stream 连接），
 * 聚合患者最新体征数据到 Map。
 */
export function useVitalSSE(options: UseVitalSSEOptions = {}): UseVitalSSEReturn {
  const { enabled = true, patientIds, onUpdate } = options;
  const [patientVitals, setPatientVitals] = useState<Map<string, PatientVital>>(new Map());
  const [lastUpdate, setLastUpdate] = useState<VitalUpdateEvent | null>(null);

  const handleVitalUpdate = useCallback(
    (data: VitalUpdateEvent) => {
      if (patientIds && patientIds.length > 0 && !patientIds.includes(data.patient_id)) {
        return;
      }

      setPatientVitals((prev) => {
        const next = new Map(prev);
        const key = `${data.patient_id}_${data.device_model ?? 'unknown'}`;
        const existing = next.get(key);
        next.set(key, {
          patient_id: data.patient_id,
          device_type: data.device_model ?? 'unknown',
          // 批量同步事件不含单值，用累计 count 表示活跃度
          latest_value: data.count > 0
            ? (existing?.latest_value ?? 0) + data.count
            : existing?.latest_value,
          updated_at: data.occurred_at ?? new Date().toISOString(),
        });
        return next;
      });
      setLastUpdate(data);
      onUpdate?.(data);
    },
    [patientIds, onUpdate],
  );

  const { connected } = useAlertSSE({
    enabled,
    onVitalUpdate: handleVitalUpdate,
  });

  return { connected, patientVitals, lastUpdate };
}
