import { useState, useEffect, useCallback } from 'react';
import { listInsights } from '../../api/copilot';
import type { CopilotInsight } from '../../api/copilot';

export function useCopilotInsights(patientId: string | undefined) {
  const [data, setData] = useState<CopilotInsight[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  const fetch = useCallback(async () => {
    if (!patientId) return;
    setLoading(true);
    try {
      const res = await listInsights({ patient_id: patientId, page_size: 20 });
      const payload = (res.data as { data?: CopilotInsight[]; total?: number }).data ?? [];
      const total = (res.data as { total?: number }).total ?? 0;
      setData(payload);
      setTotal(total);
    } catch {
      // 静默失败
    } finally {
      setLoading(false);
    }
  }, [patientId]);

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

  return { data, total, loading, refresh: fetch };
}
