import { useState, useEffect } from 'react';
import type { MarketingPlan } from '@/features/plan/types/plan';
import { getPlan } from '@/shared/api/generated/plan/plan';

interface UseMarketingPlanResult {
  data: MarketingPlan | null;
  isLoading: boolean;
  error: string | null;
  clinicId: string | null;
}

export function useMarketingPlan(id: string | undefined): UseMarketingPlanResult {
  const [data, setData] = useState<MarketingPlan | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!id) {
      setError('No plan ID provided');
      setIsLoading(false);
      return;
    }

    async function loadPlan() {
      try {
        const planRes = await getPlan(id!);
        if (planRes.status !== 200) {
          throw new Error('마케팅 기획 조회에 실패했습니다.');
        }
        const planOutput = planRes.data;
        if (!planOutput) {
          throw new Error('마케팅 기획이 아직 생성되지 않았습니다.');
        }

        // SDK PlanApiResponse 가 MarketingPlan 과 사실상 동일 — 패스스루.
        // reportId/workflow 는 SDK 에 없는 로컬 전용 필드.
        setData({
          ...(planOutput as unknown as MarketingPlan),
          id: planOutput.id || id!,
          reportId: id!,
          clinicName: planOutput.clinicName ?? '',
          clinicNameEn: planOutput.clinicNameEn ?? '',
        });
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to fetch marketing plan');
      } finally {
        setIsLoading(false);
      }
    }

    loadPlan();
  }, [id]);

  return { data, isLoading, error, clinicId: null };
}
