import { useState, useEffect } from 'react'; import { useLocation } from 'react-router'; import type { MarketingPlan } from '../types/plan'; import { fetchReportById } from '../lib/supabase'; import { transformReportToPlan } from '../lib/transformPlan'; interface UseMarketingPlanResult { data: MarketingPlan | null; isLoading: boolean; error: string | null; } interface LocationState { report?: Record; metadata?: Record; reportId?: string; } export function useMarketingPlan(id: string | undefined): UseMarketingPlanResult { const [data, setData] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const location = useLocation(); useEffect(() => { if (!id) { setError('No plan ID provided'); setIsLoading(false); return; } const state = location.state as LocationState | undefined; // Source 1: Report data passed via navigation state if (state?.report && state?.metadata) { try { const plan = transformReportToPlan({ id: (state.reportId || id), url: (state.metadata.url as string) || '', clinic_name: (state.metadata.clinicName as string) || '', report: state.report, created_at: (state.metadata.generatedAt as string) || new Date().toISOString(), }); setData(plan); setIsLoading(false); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to build marketing plan'); setIsLoading(false); } return; } // Source 2: Fetch report from Supabase and transform to plan fetchReportById(id) .then((row) => { const plan = transformReportToPlan(row); setData(plan); }) .catch((err) => { setError(err instanceof Error ? err.message : 'Failed to fetch marketing plan'); }) .finally(() => setIsLoading(false)); }, [id, location.state]); return { data, isLoading, error }; }