import { useCallback } from 'react';
import type { MarketingReport } from '@/features/report/types/report';

/**
 * 리포트의 표 데이터 전체를 단일 CSV로 내보내는 훅.
 * 섹션 사이는 빈 행 하나 + 섹션 제목 행으로 구분 (Excel에서 자연스럽게 보이도록).
 * Excel/Numbers에서 한글이 깨지지 않도록 UTF-8 BOM 포함.
 */

type Cell = string | number | null | undefined;
type Row = Cell[];
type Section = { title: string; rows: Row[] };

function escapeCell(value: Cell): string {
  const s = String(value ?? '');
  if (/[",\n\r]/.test(s)) {
    return `"${s.replace(/"/g, '""')}"`;
  }
  return s;
}

function buildReportCsv(report: MarketingReport): string {
  const sections: Section[] = [];

  // ─── KPI Dashboard ───
  if (report.kpiDashboard?.length) {
    sections.push({
      title: 'KPI Dashboard',
      rows: [
        ['Metric', 'Current', '3-Month Target', '12-Month Target'],
        ...report.kpiDashboard.map((m) => [m.metric, m.current, m.target3Month, m.target12Month]),
      ],
    });
  }

  // ─── Channel Scores ───
  if (report.channelScores?.length) {
    sections.push({
      title: 'Channel Scores',
      rows: [
        ['Channel', 'Score', 'Max Score', 'Status', 'Headline'],
        ...report.channelScores.map((c) => [c.channel, c.score, c.maxScore, c.status, c.headline]),
      ],
    });
  }

  // ─── Problem Diagnosis ───
  if (report.problemDiagnosis?.length) {
    sections.push({
      title: 'Problem Diagnosis',
      rows: [
        ['Category', 'Detail', 'Severity'],
        ...report.problemDiagnosis.map((d) => [d.category, d.detail, d.severity]),
      ],
    });
  }

  // ─── Roadmap (월별 → 태스크 단위로 풀어 펼침) ───
  if (report.roadmap?.length) {
    const rows: Row[] = [['Month', 'Title', 'Subtitle', 'Task', 'Completed']];
    report.roadmap.forEach((m) => {
      if (m.tasks.length === 0) {
        rows.push([m.month, m.title, m.subtitle, '', '']);
        return;
      }
      m.tasks.forEach((t, i) => {
        rows.push([
          i === 0 ? m.month : '',
          i === 0 ? m.title : '',
          i === 0 ? m.subtitle : '',
          t.task,
          t.completed ? 'Y' : 'N',
        ]);
      });
    });
    sections.push({ title: 'Roadmap', rows });
  }

  // ─── Transformation ───
  const t = report.transformation;
  const asIsToBe = (title: string, items: { area: string; asIs: string; toBe: string }[]) => {
    if (!items?.length) return;
    sections.push({
      title,
      rows: [['Area', 'As-Is', 'To-Be'], ...items.map((i) => [i.area, i.asIs, i.toBe])],
    });
  };
  asIsToBe('Transformation: Brand Identity', t?.brandIdentity ?? []);
  asIsToBe('Transformation: Content Strategy', t?.contentStrategy ?? []);
  asIsToBe('Transformation: Website Improvements', t?.websiteImprovements ?? []);

  if (t?.newChannelProposals?.length) {
    sections.push({
      title: 'Transformation: New Channel Proposals',
      rows: [
        ['Channel', 'Priority', 'Rationale'],
        ...t.newChannelProposals.map((p) => [p.channel, p.priority, p.rationale]),
      ],
    });
  }

  if (t?.platformStrategies?.length) {
    const rows: Row[] = [['Platform', 'Current Metric', 'Target Metric', 'Strategy', 'Detail']];
    t.platformStrategies.forEach((p) => {
      if (p.strategies.length === 0) {
        rows.push([p.platform, p.currentMetric, p.targetMetric, '', '']);
        return;
      }
      p.strategies.forEach((s, i) => {
        rows.push([
          i === 0 ? p.platform : '',
          i === 0 ? p.currentMetric : '',
          i === 0 ? p.targetMetric : '',
          s.strategy,
          s.detail,
        ]);
      });
    });
    sections.push({ title: 'Transformation: Platform Strategies', rows });
  }

  // ─── Channel diagnoses ───
  const diagSection = (title: string, items: { category: string; detail: string; severity: string }[]) => {
    if (!items?.length) return;
    sections.push({
      title,
      rows: [['Category', 'Detail', 'Severity'], ...items.map((d) => [d.category, d.detail, d.severity])],
    });
  };
  diagSection('YouTube Diagnosis', report.youtubeAudit?.diagnosis ?? []);
  diagSection('Instagram Diagnosis', report.instagramAudit?.diagnosis ?? []);
  diagSection('Facebook Diagnosis', report.facebookAudit?.diagnosis ?? []);

  // ─── Facebook Brand Inconsistencies (채널별 값으로 풀어 펼침) ───
  if (report.facebookAudit?.brandInconsistencies?.length) {
    const rows: Row[] = [['Field', 'Channel', 'Value', 'Correct', 'Impact', 'Recommendation']];
    report.facebookAudit.brandInconsistencies.forEach((b) => {
      b.values.forEach((v, i) => {
        rows.push([
          i === 0 ? b.field : '',
          v.channel,
          v.value,
          v.isCorrect ? 'Y' : 'N',
          i === 0 ? b.impact : '',
          i === 0 ? b.recommendation : '',
        ]);
      });
    });
    sections.push({ title: 'Facebook Brand Inconsistencies', rows });
  }

  // ─── Instagram Accounts (요약 컬럼만) ───
  if (report.instagramAudit?.accounts?.length) {
    sections.push({
      title: 'Instagram Accounts',
      rows: [
        ['Handle', 'Language', 'Label', 'Followers', 'Following', 'Posts', 'Reels', 'Category'],
        ...report.instagramAudit.accounts.map((a) => [
          a.handle,
          a.language,
          a.label,
          a.followers,
          a.following,
          a.posts,
          a.reelsCount,
          a.category,
        ]),
      ],
    });
  }

  // ─── Facebook Pages (요약 컬럼만) ───
  if (report.facebookAudit?.pages?.length) {
    sections.push({
      title: 'Facebook Pages',
      rows: [
        ['Page Name', 'Language', 'Label', 'Followers', 'Reviews', 'Category', 'URL'],
        ...report.facebookAudit.pages.map((p) => [
          p.pageName,
          p.language,
          p.label,
          p.followers,
          p.reviews,
          p.category,
          p.url,
        ]),
      ],
    });
  }

  // ─── Other Channels ───
  if (report.otherChannels?.length) {
    sections.push({
      title: 'Other Channels',
      rows: [
        ['Name', 'Status', 'Details', 'URL'],
        ...report.otherChannels.map((c) => [c.name, c.status, c.details, c.url ?? '']),
      ],
    });
  }

  // ─── Website Audit (단일 행 요약) ───
  if (report.websiteAudit) {
    const w = report.websiteAudit;
    sections.push({
      title: 'Website Audit',
      rows: [
        ['Primary Domain', 'Main CTA', 'SNS Links On Site'],
        [w.primaryDomain, w.mainCTA, w.snsLinksOnSite ? 'Y' : 'N'],
      ],
    });
    if (w.trackingPixels?.length) {
      sections.push({
        title: 'Website: Tracking Pixels',
        rows: [['Name', 'Installed'], ...w.trackingPixels.map((p) => [p.name, p.installed ? 'Y' : 'N'])],
      });
    }
  }

  // ─── 출력 조립: Excel에서 보기 좋도록 빈 행 + 섹션 제목(한 셀) + 데이터 ───
  const lines: string[] = [];
  sections.forEach((sec, idx) => {
    if (idx > 0) lines.push('');
    lines.push(escapeCell(sec.title));
    sec.rows.forEach((row) => lines.push(row.map(escapeCell).join(',')));
  });

  return lines.join('\r\n');
}

export function useExportCSV() {
  const exportReportCSV = useCallback((filename: string, report: MarketingReport) => {
    const csv = '﻿' + buildReportCsv(report); // Excel 한글 깨짐 방지 BOM
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = `${filename}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);

    URL.revokeObjectURL(url);
  }, []);

  return { exportReportCSV };
}
