import { useState, useEffect } from 'react';
import { useLocation } from 'react-router';
import type { MarketingReport } from '../types/report';
import { fetchReportById } from '../lib/supabase';
import { transformApiReport, mergeEnrichment, type EnrichmentData } from '../lib/transformReport';
import { normalizeInstagramHandle } from '../lib/normalizeHandles';
import { mockReport } from '../data/mockReport';

interface UseReportResult {
  data: MarketingReport | null;
  isLoading: boolean;
  error: string | null;
  /** True if channelEnrichment was already in the DB — no need to re-enrich */
  isEnriched: boolean;
  /** Normalized social handles recovered from DB or API metadata */
  socialHandles: Record<string, string | null> | null;
}

interface LocationState {
  report?: Record<string, unknown>;
  metadata?: {
    url: string;
    clinicName: string;
    generatedAt: string;
    socialHandles?: Record<string, string | null>;
    address?: string;
    services?: string[];
  };
  reportId?: string;
}

export function useReport(id: string | undefined): UseReportResult {
  const [data, setData] = useState<MarketingReport | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isEnriched, setIsEnriched] = useState(false);
  const [socialHandles, setSocialHandles] = useState<Record<string, string | null> | null>(null);
  const location = useLocation();

  useEffect(() => {
    // Source 0: Demo mode — ALWAYS takes priority over any other source
    if (id === 'view-clinic') {
      setData(mockReport);
      setIsEnriched(true);
      setSocialHandles({ instagram: '@viewplastic', youtube: '@ViewclinicKR', facebook: 'viewps1' });
      setIsLoading(false);
      return;
    }

    const state = location.state as LocationState | undefined;

    // Source 1: Report data passed via navigation state (from AnalysisLoadingPage)
    if (state?.report && state?.metadata) {
      try {
        const reportId = state.reportId || id || 'live';
        const transformed = transformApiReport(
          reportId,
          state.report,
          state.metadata,
        );
        // V2 pipeline: report already includes channelEnrichment from Phase 2
        const enrichment = state.report.channelEnrichment as EnrichmentData | undefined;
        if (enrichment) {
          const merged = mergeEnrichment(transformed, enrichment);
          setData(merged);
          setIsEnriched(true);
        } else {
          setData(transformed);
          setIsEnriched(false);
        }
        setSocialHandles(state.metadata.socialHandles || null);
        setIsLoading(false);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to parse report data');
        setIsLoading(false);
      }
      return;
    }

    // Source 2: Fetch from Supabase by report ID (bookmarked/shared link)
    if (id) {
      fetchReportById(id)
        .then((row) => {
          const reportJson = row.report as Record<string, unknown>;

          // V2 pipeline: if report is empty but status is not 'complete', show message
          if (!reportJson || Object.keys(reportJson).length === 0 || reportJson.parseError) {
            const status = (row as Record<string, unknown>).status as string | undefined;
            if (status && status !== 'complete') {
              throw new Error(`리포트 생성 중입니다 (${status}). 잠시 후 새로고침 해주세요.`);
            }
            throw new Error('리포트 데이터가 비어있습니다. 분석을 다시 실행해주세요.');
          }

          const scrapeData = row.scrape_data as Record<string, unknown> | undefined;

          const transformed = transformApiReport(
            row.id,
            reportJson,
            {
              url: row.url,
              clinicName: row.clinic_name || '',
              generatedAt: row.created_at,
              // Pass Registry metadata so ClinicSnapshot can show verified badge + district
              source: (scrapeData?.source as 'registry' | 'scrape' | undefined) ?? 'scrape',
              registryData: (scrapeData?.registryData as Record<string, string> | null | undefined) ?? null,
            },
          );

          // Recover social handles: report.socialHandles > AI clinicInfo.socialMedia > scrape_data
          let handles = (reportJson.socialHandles as Record<string, string | null | string[]>) || null;
          if (!handles) {
            // Try AI-generated socialMedia in clinicInfo
            const aiSocial = (reportJson.clinicInfo as Record<string, unknown>)?.socialMedia as Record<string, unknown> | undefined;
            const scrapeSocial = scrapeData
              ? (scrapeData.clinic as Record<string, unknown>)?.socialMedia as Record<string, string> | undefined
              : undefined;

            const igSource = aiSocial?.instagramAccounts || aiSocial?.instagram || scrapeSocial?.instagram;
            const ytSource = (aiSocial?.youtube as string) || scrapeSocial?.youtube;

            if (igSource || ytSource) {
              handles = {
                instagram: Array.isArray(igSource)
                  ? igSource.map((h: string) => normalizeInstagramHandle(h)).filter(Boolean)
                  : normalizeInstagramHandle(igSource as string),
                youtube: ytSource || null,
                facebook: (aiSocial?.facebook as string) || scrapeSocial?.facebook || null,
                blog: (aiSocial?.naverBlog as string) || scrapeSocial?.blog || null,
              };
            }
          }
          setSocialHandles(handles as Record<string, string | null> | null);

          // V2: channel_data column (separate from report JSONB)
          // V1 compat: channelEnrichment inside report JSONB
          const enrichment =
            (row.channel_data && Object.keys(row.channel_data).length > 0 ? row.channel_data : null) as EnrichmentData | null
            || (reportJson.channelEnrichment as EnrichmentData | undefined)
            || null;

          if (enrichment) {
            const merged = mergeEnrichment(transformed, enrichment);
            setData(merged);
            setIsEnriched(true);
          } else {
            setData(transformed);
            setIsEnriched(false);
          }
        })
        .catch((err) => {
          setError(err instanceof Error ? err.message : 'Failed to fetch report');
        })
        .finally(() => setIsLoading(false));
      return;
    }

    // No data source available
    setError('리포트 데이터를 찾을 수 없습니다. 새 분석을 시작해주세요.');
    setIsLoading(false);
  }, [id, location.state]);

  return { data, isLoading, error, isEnriched, socialHandles };
}
