"use client";

/**
 * Written Report — Professional SEO Performance Report
 * ─────────────────────────────────────────────────────
 * Clean, client-ready report with charts, KPI cards, findings.
 * Data from the same Analysis object as the Live Artifact.
 */

import { useState } from "react";
import type { Analysis, ChartSpec } from "@/lib/services/analysis-schema";
import { buildReportDocument, renderToMarkdown } from "@/lib/services/report-export";
import {
  ResponsiveContainer, LineChart, Line, BarChart, Bar,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend,
} from "recharts";
import {
  Download, Copy, Check, X, FileText, AlertTriangle, AlertCircle, Info,
  TrendingUp, TrendingDown, Minus, CheckCircle2, Printer,
} from "lucide-react";
import { MarkdownContent } from "@/components/shared/MarkdownContent";

function fmtDate(d: string): string {
  try { const p = new Date(d); return isNaN(p.getTime()) ? d : p.toLocaleDateString("en-US", { month: "short", day: "numeric" }); } catch { return d; }
}

function shortPath(url: string): string {
  try {
    const p = new URL(url).pathname.replace(/\/$/, "");
    if (p.length <= 35) return p || "/";
    const segments = p.split("/").filter(Boolean);
    const last = segments[segments.length - 1] || "";
    return last.length > 30 ? "/" + last.slice(0, 28) + "…" : "/" + (segments.length > 1 ? "…/" : "") + last;
  } catch { return url.length > 35 ? url.slice(0, 33) + "…" : url; }
}

// ── Report Chart Component ──
function ReportChart({ chart }: { chart: ChartSpec }) {
  const data = chart.data.filter((d) => {
    const clicks = Number(d.clicks ?? d.sessions ?? 0);
    const imps = Number(d.impressions ?? d.conversions ?? 0);
    return clicks > 0 || imps > 0;
  });
  if (data.length < 2) return null;
  const xKey = chart.xAxis.key;
  return (
    <div className="print:break-inside-avoid">
      <ResponsiveContainer width="100%" height={380}>
        <LineChart data={data} margin={{ top: 10, right: 20, left: 5, bottom: 5 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="#E5E7EB" strokeOpacity={0.5} />
          <XAxis dataKey={xKey} tick={{ fontSize: 11, fill: "#374151" }} tickFormatter={fmtDate} minTickGap={30} />
          <YAxis yAxisId="left" tick={{ fontSize: 11, fill: "#374151" }} width={50} tickFormatter={(v: number) => v >= 1_000_000 ? `${(v / 1_000_000).toFixed(1)}M` : v >= 1000 ? `${(v / 1000).toFixed(0)}k` : String(v)} />
          {chart.yAxes.length > 1 && <YAxis yAxisId="right" orientation="right" tick={{ fontSize: 11, fill: "#374151" }} width={50} tickFormatter={(v: number) => v >= 1_000_000 ? `${(v / 1_000_000).toFixed(1)}M` : v >= 1000 ? `${(v / 1000).toFixed(0)}k` : String(v)} />}
          <Tooltip contentStyle={{ backgroundColor: "#fff", border: "1px solid #E5E7EB", fontSize: 11, borderRadius: 8 }} labelFormatter={(l) => fmtDate(String(l))} formatter={(v) => typeof v === "number" ? v.toLocaleString() : String(v)} />
          <Legend wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
          {chart.yAxes.map((axis, i) => (
            <Line key={axis.key} yAxisId={i === 0 ? "left" : "right"} type="monotone" dataKey={axis.key} name={axis.label} stroke={axis.color} strokeWidth={2} dot={false} />
          ))}
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

// ── Top Pages Horizontal Bar Chart ──
function TopPagesChart({ chart }: { chart: ChartSpec }) {
  const data = chart.data.filter((d) => Number(d.clicks ?? 0) > 5).slice(0, 10).map((d) => ({
    ...d,
    page: shortPath(String(d.page ?? "")),
    fullPage: String(d.page ?? ""),
  }));
  if (data.length < 2) return null;
  return (
    <div className="print:break-inside-avoid">
      <ResponsiveContainer width="100%" height={Math.max(350, data.length * 44)}>
        <BarChart data={data} layout="vertical" margin={{ top: 5, right: 50, left: 10, bottom: 5 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="#E5E7EB" strokeOpacity={0.3} horizontal={false} />
          <XAxis type="number" tick={{ fontSize: 11, fill: "#6B7280" }} tickFormatter={(v: number) => v >= 1000 ? `${(v / 1000).toFixed(1)}k` : String(v)} />
          <YAxis type="category" dataKey="page" tick={{ fontSize: 11, fill: "#374151" }} width={240} />
          <Tooltip contentStyle={{ fontSize: 11, borderRadius: 8 }} labelFormatter={(v) => data.find((d) => d.page === String(v))?.fullPage ?? String(v)} formatter={(v) => typeof v === "number" ? v.toLocaleString() : String(v)} />
          <Bar dataKey="clicks" fill="#3B82F6" radius={[0, 4, 4, 0]} />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

export function NarrativeReport({ analysis, onClose }: { analysis: Analysis; onClose?: () => void }) {
  const [copied, setCopied] = useState(false);
  const [downloading, setDownloading] = useState<"docx" | "pdf" | null>(null);

  function copyMarkdown() {
    const doc = buildReportDocument(analysis);
    navigator.clipboard.writeText(renderToMarkdown(doc)).then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); });
  }

  function printReport() { window.print(); }

  const b = analysis.branding;
  const n = analysis.narrative;
  const sources = analysis.sources.filter(s => s.status === "available").map(s => s.label).join(" · ") || "No sources";

  // Find chart data from analysis object
  const gscChart = analysis.charts?.find((c) => c.id === "chart_gsc" || c.title?.toLowerCase().includes("organic"));
  const ga4Chart = analysis.charts?.find((c) => c.id === "chart_ga4" || c.title?.toLowerCase().includes("traffic"));
  const topPagesChart = analysis.charts?.find((c) => c.id === "chart_top_pages" || c.title?.toLowerCase().includes("top pages"));

  let sectionNum = 0;
  const nextNum = () => String(++sectionNum).padStart(2, "0");

  return (
    <div className="h-full overflow-y-auto bg-slate-50 print:bg-white">
      <div className="max-w-[900px] mx-auto bg-white shadow-sm print:shadow-none print:max-w-none">

        {/* ═══ HEADER ═══ */}
        <div className="sticky top-0 z-10 bg-white border-b border-slate-200 print:static print:border-0">
          <div className="px-10 py-5 flex items-start justify-between">
            <div className="flex items-start gap-4">
              {b?.clientLogoUrl ? (
                <img src={b.clientLogoUrl} alt={b.clientName} className="w-11 h-11 rounded-lg object-contain border border-slate-100 shrink-0" />
              ) : (
                <div className="w-11 h-11 rounded-lg bg-slate-900 flex items-center justify-center shrink-0">
                  <span className="text-sm font-bold text-white">{(b?.clientName ?? "?").slice(0, 2).toUpperCase()}</span>
                </div>
              )}
              <div>
                <p className="text-[9px] font-bold uppercase tracking-[0.2em] text-slate-400">{b?.appBrand ?? "meSEO"} Analysis Report</p>
                <h1 className="text-lg font-bold text-slate-900 mt-0.5">{b?.clientName ?? analysis.title}</h1>
                <p className="text-xs text-slate-400 mt-0.5">{b?.clientDomain} · {analysis.period.start} to {analysis.period.end} · {sources}</p>
              </div>
            </div>
            <div className="flex items-center gap-1 print:hidden shrink-0">
              <button onClick={printReport} className="px-2.5 py-1.5 text-[10px] font-semibold text-slate-500 hover:bg-slate-100 rounded-md">
                <Printer className="w-3 h-3 inline mr-1" />Print / PDF
              </button>
              {(["docx"] as const).map(fmt => (
                <button key={fmt} onClick={async () => { setDownloading(fmt); try { const res = await fetch(`/api/analysis/export?brandId=${analysis.brandId}&format=${fmt}`); if (res.ok) { const blob = await res.blob(); const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = `${b?.clientDomain ?? "report"}-analysis.${fmt}`; a.click(); } } catch {} setDownloading(null); }} disabled={!!downloading} className="px-2.5 py-1.5 text-[10px] font-semibold text-slate-500 hover:bg-slate-100 rounded-md disabled:opacity-50">
                  <Download className="w-3 h-3 inline mr-1" />{downloading === fmt ? "..." : fmt.toUpperCase()}
                </button>
              ))}
              <button onClick={copyMarkdown} className="px-2.5 py-1.5 text-[10px] font-semibold text-slate-500 hover:bg-slate-100 rounded-md">
                {copied ? <Check className="w-3 h-3 inline mr-1 text-green-600" /> : <Copy className="w-3 h-3 inline mr-1" />}{copied ? "Copied" : "Copy"}
              </button>
              {onClose && <button onClick={onClose} className="text-slate-300 hover:text-slate-500 p-1 ml-1"><X className="w-4 h-4" /></button>}
            </div>
          </div>
        </div>

        <div className="px-10 py-10 space-y-12">

          {/* ═══ EXECUTIVE SUMMARY ═══ */}
          <section className="print:break-inside-avoid">
            <SectionTitle num={nextNum()}>Executive Summary</SectionTitle>
            {n?.executiveSummary ? (
              <div className="border-l-4 border-brand-500 bg-slate-50 rounded-r-lg px-6 py-5">
                <MarkdownContent className="text-[15px] text-slate-700 leading-[1.8]">
                  {n.executiveSummary}
                </MarkdownContent>
              </div>
            ) : <Empty />}
            <div className="flex items-center gap-4 mt-4 text-xs text-slate-400">
              <span>{analysis.sources.filter(s => s.status === "available").length} sources</span>
              <span>{analysis.findings.length} findings</span>
              <span>{analysis.recommendations.length} recommendations</span>
            </div>
          </section>

          {/* ═══ KPI DASHBOARD ═══ */}
          <section className="print:break-inside-avoid">
            <SectionTitle num={nextNum()}>Key Performance Indicators</SectionTitle>
            {(() => {
              // Hide Bounce Rate from display — see comment in kpi-cards.tsx.
              const visibleKpis = analysis.kpis.filter((k) => !/bounce\s*rate/i.test(k.label));
              return visibleKpis.length > 0 ? (
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
                {visibleKpis.map((kpi, i) => {
                  const isUp = kpi.change?.direction === "up";
                  const isDown = kpi.change?.direction === "down";
                  const isNew = kpi.change?.label?.toLowerCase().startsWith("new");
                  return (
                    <div key={i} className="bg-[#FAFAFA] rounded-lg border border-[#E5E7EB] p-6 min-h-[130px] flex flex-col justify-between relative">
                      <div>
                        <div className="flex items-center justify-between mb-2">
                          <p className="text-[13px] font-semibold text-[#6B7280] uppercase tracking-wider">{kpi.label}</p>
                          <span className="text-[9px] font-bold text-slate-300 bg-slate-100 rounded px-1.5 py-0.5">{kpi.source}</span>
                        </div>
                        <p className="text-[32px] font-bold text-[#1A1A1A] leading-none">{kpi.value}{kpi.unit && <span className="text-lg font-normal text-slate-400 ml-1">{kpi.unit}</span>}</p>
                      </div>
                      <div className="mt-3">
                        {kpi.change && !isNew && (
                          <span className={`inline-flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${isUp ? "text-[#22C55E] bg-green-50" : isDown ? "text-[#EF4444] bg-red-50" : "text-slate-400 bg-slate-100"}`}>
                            {isUp ? <TrendingUp className="w-3 h-3" /> : isDown ? <TrendingDown className="w-3 h-3" /> : <Minus className="w-3 h-3" />}
                            {kpi.change.value > 0 ? "+" : ""}{kpi.change.value}%
                          </span>
                        )}
                        {isNew && <span className="text-[11px] font-semibold text-slate-400 bg-slate-100 rounded-full px-2 py-0.5">New data</span>}
                        {kpi.previousValue && <p className="text-[12px] text-slate-400 mt-1">Previous: {kpi.previousValue}</p>}
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : <Empty />;
            })()}
          </section>

          {/* ═══ ORGANIC SEARCH CHART ═══ */}
          {gscChart && (
            <section>
              <SectionTitle num={nextNum()}>Organic Search Performance</SectionTitle>
              <ReportChart chart={gscChart} />
            </section>
          )}

          {/* ═══ TRAFFIC & CONVERSIONS CHART ═══ */}
          {ga4Chart && (
            <section>
              <SectionTitle num={nextNum()}>Traffic &amp; Conversions</SectionTitle>
              <ReportChart chart={ga4Chart} />
            </section>
          )}

          {/* ═══ TOP PAGES CHART ═══ */}
          {topPagesChart && (
            <section>
              <SectionTitle num={nextNum()}>Top Pages by Organic Clicks</SectionTitle>
              <TopPagesChart chart={topPagesChart} />
            </section>
          )}

          {/* ═══ FINDINGS ═══ */}
          {analysis.findings.length > 0 && (
            <section>
              <SectionTitle num={nextNum()}>Findings</SectionTitle>
              <div className="space-y-4">
                {analysis.findings.map((f) => {
                  const sev = f.severity;
                  const Icon = sev === "critical" ? AlertCircle : sev === "high" ? AlertTriangle : sev === "low" ? CheckCircle2 : Info;
                  const color = sev === "critical" ? "border-[#EF4444] bg-red-50" : sev === "high" ? "border-[#F59E0B] bg-amber-50" : sev === "low" ? "border-[#22C55E] bg-green-50" : "border-[#3B82F6] bg-blue-50";
                  const iconColor = sev === "critical" ? "text-[#EF4444]" : sev === "high" ? "text-[#F59E0B]" : sev === "low" ? "text-[#22C55E]" : "text-[#3B82F6]";
                  return (
                    <div key={f.id} className={`border-l-4 rounded-r-lg px-5 py-4 ${color} print:break-inside-avoid`}>
                      <div className="flex items-start gap-2.5">
                        <Icon className={`w-4 h-4 shrink-0 mt-0.5 ${iconColor}`} />
                        <div>
                          <p className="text-sm font-semibold text-slate-800">{f.title} <span className="text-[9px] font-bold uppercase text-slate-400 ml-1">{sev}</span></p>
                          <MarkdownContent className="text-sm text-slate-600 mt-0.5">{f.description}</MarkdownContent>
                          {f.evidence && <p className="text-xs text-slate-400 mt-2 font-mono">{f.evidence}</p>}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </section>
          )}

          {/* ═══ RECOMMENDATIONS ═══ */}
          {analysis.recommendations.length > 0 && (
            <section>
              <SectionTitle num={nextNum()}>Recommendations</SectionTitle>
              <div className="space-y-4">
                {analysis.recommendations.map((r, i) => (
                  <div key={i} className="flex gap-4 print:break-inside-avoid">
                    <span className={`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 text-xs font-bold ${r.priority === "critical" ? "bg-red-100 text-red-700" : r.priority === "high" ? "bg-orange-100 text-orange-700" : "bg-slate-100 text-slate-600"}`}>{i + 1}</span>
                    <div>
                      <p className="text-sm font-semibold text-slate-800">{r.title} <span className={`text-[9px] font-bold uppercase ${r.priority === "critical" ? "text-red-500" : r.priority === "high" ? "text-orange-500" : "text-slate-400"}`}>{r.priority}</span></p>
                      <MarkdownContent className="text-sm text-slate-600 mt-0.5">{r.description}</MarkdownContent>
                      {r.expectedImpact && <MarkdownContent className="text-xs text-[#22C55E] font-medium mt-1">{r.expectedImpact}</MarkdownContent>}
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* ═══ OUTLOOK ═══ */}
          {analysis.predictions.length > 0 && (
            <section>
              <SectionTitle num={nextNum()}>Outlook</SectionTitle>
              <div className="bg-[#FAFAFA] rounded-lg border border-[#E5E7EB] divide-y divide-[#E5E7EB]">
                {analysis.predictions.map((p, i) => (
                  <div key={i} className="px-5 py-4 print:break-inside-avoid">
                    <p className="text-sm font-semibold text-slate-800">{p.metric} <span className={`text-[10px] font-semibold rounded-full px-2 py-0.5 ${p.confidence === "high" ? "bg-green-100 text-green-700" : "bg-slate-100 text-slate-500"}`}>{p.confidence}</span></p>
                    <p className="text-sm text-slate-600 mt-1">Projected: <strong className="text-slate-900">{p.predicted.toLocaleString()}</strong> vs current {p.current.toLocaleString()}</p>
                    <p className="text-xs text-slate-400 mt-1">{p.timeframe} · {p.basis}</p>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* ═══ FOOTER ═══ */}
          <footer className="border-t border-slate-200 pt-8 text-center print:pt-12">
            <p className="text-[9px] text-slate-300 uppercase tracking-[0.2em] font-bold">{b?.appBrand ?? "meSEO"}</p>
            <p className="text-[10px] text-slate-400 mt-1">Generated {b?.reportDate} · {b?.clientName} · {b?.clientDomain}</p>
          </footer>
        </div>
      </div>
    </div>
  );
}

function SectionTitle({ num, children }: { num: string; children: React.ReactNode }) {
  return (
    <div className="flex items-center gap-3 mb-5 pb-3 border-b border-[#E5E7EB]">
      <span className="text-[13px] font-bold text-slate-300">{num}</span>
      <h2 className="text-[20px] font-semibold text-slate-900">{children}</h2>
    </div>
  );
}

function Empty() {
  return (
    <div className="bg-slate-50 rounded-lg border border-dashed border-slate-200 px-6 py-8 text-center">
      <FileText className="w-5 h-5 text-slate-200 mx-auto mb-1" />
      <p className="text-xs text-slate-400">No data available. Generate an analysis first.</p>
    </div>
  );
}
