'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();
  }, [planId, load]);

  return { state, refresh: load };
}
