'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { ApiError } from '@/lib/api-client';
import type { PlanDetailData } from '@/components/plan-detail/plan-detail-types';
import { plansApi } from './plans-api';

export type AggregateState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'ready'; data: PlanDetailData }
  | { status: 'error'; message: string; code?: number };

export function usePlanAggregate(planId: string) {
  const [state, setState] = useState<AggregateState>({ status: 'idle' });

  const load = useCallback(async () => {
    setState({ status: 'loading' });
    try {
      const data = await plansApi.getAggregate(planId);
      setState({ status: 'ready', data });
    } catch (err) {
      if (err instanceof ApiError) {
        setState({ status: 'error', message: err.message, code: err.code });
      } else {
        setState({ status: 'error', message: err instanceof Error ? err.message : String(err) });
      }
    }
  }, [planId]);

  // 去重守卫:同一 planId 自动加载只触发一次 —— 规避 React 18 StrictMode(dev)
  // 双调 effect 导致 /full 请求两次。planId 变化时重置;手动 refresh 不受限。
  const loadedFor = useRef<string | null>(null);
  useEffect(() => {
    if (loadedFor.current === planId) return;
    loadedFor.current = planId;
    void load();
    // ⭐ PV/UV 埋点:借这道守卫定义「进入一次详情页」——
    //   三种入口全收(直接进/刷新 · 患者列表切换 · /plans 落地自动跳转),
    //   而**手动 refresh 不重复计**(refresh 直接调 load(),走不到这里)。
    //   尽力而为:失败只吞掉,埋点不能影响页面。
    void plansApi.reportView(planId).catch(() => {});
  }, [planId, load]);

  return { state, refresh: load };
}
