import { View, Text, StyleSheet } from "@react-pdf/renderer";
import { C, S } from "../styles";
import type { RevenueAttribution } from "../../types";

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, marginBottom: 16, color: C.muted },
  // Confidence pill
  pill: { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2, alignSelf: "flex-start", marginBottom: 14 },
  pillText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.8 },
  // Metrics strip
  metricsRow: { flexDirection: "row", gap: 8, marginBottom: 20 },
  metricBox: { flex: 1, borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 10, alignItems: "center" },
  metricValue: { fontSize: 14, fontFamily: "Helvetica-Bold", color: C.ink, textAlign: "center" },
  metricLabel: { fontSize: 7, color: C.muted, textAlign: "center", marginTop: 2 },
  metricSub: { fontSize: 6.5, color: C.muted, textAlign: "center", marginTop: 1 },
  // Section wrapper
  section: { marginBottom: 18 },
  sectionHeading: { fontSize: 10, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 8 },
  // Table
  table: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, overflow: "hidden", marginBottom: 6 },
  headerRow: { flexDirection: "row", backgroundColor: C.surface, paddingHorizontal: 10, paddingVertical: 6, borderBottomWidth: 0.75, borderBottomColor: C.border },
  tableRow: { flexDirection: "row", paddingHorizontal: 10, paddingVertical: 5, borderBottomWidth: 0.5, borderBottomColor: "#f1f5f9", alignItems: "center" },
  rowAlt: { backgroundColor: "#fafafa" },
  rowAi: { backgroundColor: "#eef2ff" },
  colHeader: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.6 },
  cellText: { fontSize: 8.5, color: C.body },
  cellBold: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink },
  cellMuted: { fontSize: 7.5, color: C.muted },
  // AI engine cards
  engineGrid: { flexDirection: "row", flexWrap: "wrap", gap: 8, marginBottom: 6 },
  engineCard: { width: "30%", borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8, backgroundColor: "#eef2ff" },
  engineName: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 4 },
  engineRevenue: { fontSize: 13, fontFamily: "Helvetica-Bold", color: "#4f46e5", marginBottom: 4 },
  engineRow: { flexDirection: "row", justifyContent: "space-between", marginBottom: 2 },
  engineLabel: { fontSize: 7, color: C.muted },
  engineValue: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.ink },
  enginePage: { fontSize: 6.5, color: C.muted, marginTop: 3 },
  // Insights
  insightBlock: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 10, marginBottom: 8, backgroundColor: C.surface },
  insightText: { fontSize: 8.5, color: C.body, marginBottom: 3, lineHeight: 1.4 },
  insightMetric: { fontSize: 7.5, color: C.muted, marginBottom: 2 },
  insightImplication: { fontSize: 7.5, color: "#4f46e5" },
  // Delta badge
  deltaUp: { fontSize: 7, color: "#059669", fontFamily: "Helvetica-Bold" },
  deltaDown: { fontSize: 7, color: "#dc2626", fontFamily: "Helvetica-Bold" },
  // Patent
  patent: { fontSize: 7.5, color: C.muted, fontStyle: "italic", marginBottom: 12 },
  // Future caps
  futureBox: { borderWidth: 0.5, borderColor: C.border, borderRadius: 4, padding: 8, backgroundColor: C.surface },
  futureTitle: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, marginBottom: 4 },
  futureText: { fontSize: 7, color: C.muted, lineHeight: 1.4, marginBottom: 2 },

});

// ─── Helpers ──────────────────────────────────────────────────────────────────

function fmtUsd(n: number): string {
  if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `$${(n / 1_000).toFixed(1)}K`;
  return `$${n.toFixed(0)}`;
}

function urlPath(url: string): string {
  let path = url;
  try { path = new URL(url).pathname || "/"; } catch { /* keep original */ }
  return path.length > 40 ? path.slice(0, 39) + "…" : path;
}

// ─── Confidence pill ──────────────────────────────────────────────────────────

function ConfidencePill({ level }: { level: string }) {
  const cfg: Record<string, { label: string; bg: string; color: string }> = {
    high:         { label: "High confidence",    bg: "#d1fae5", color: "#065f46" },
    moderate:     { label: "Moderate confidence", bg: "#fef3c7", color: "#92400e" },
    low:          { label: "Limited data",        bg: C.surface, color: C.muted },
    insufficient: { label: "Insufficient data",   bg: C.surface, color: C.muted },
  };
  const c = cfg[level] ?? cfg.low;
  return (
    <View style={[s.pill, { backgroundColor: c.bg }]}>
      <Text style={[s.pillText, { color: c.color }]}>{c.label.toUpperCase()}</Text>
    </View>
  );
}

// Revenue tracking finding removed: most brands do not configure revenue events; absence is not a meaningful audit signal

// ─── Full content ─────────────────────────────────────────────────────────────

function FullRevenueContent({ ra }: { ra: RevenueAttribution }) {
  const agg = ra.aggregateMetrics;

  return (
    <>
      <ConfidencePill level={ra.dataConfidence} />

      {/* Aggregate metrics strip */}
      <View style={s.metricsRow} wrap={false}>
        {([
          { label: "Revenue Tracked", value: fmtUsd(agg.totalRevenueTracked) },
          { label: "Conversions w/ Revenue", value: agg.totalConversionsWithRevenue.toString() },
          { label: "Avg / Conversion", value: fmtUsd(agg.avgRevenuePerConversion) },
          { label: "Tracking Coverage", value: `${agg.revenueTrackingCoveragePercent}%`, sub: agg.conversionsMissingRevenue > 0 ? `${agg.conversionsMissingRevenue} without revenue` : undefined },
        ] as Array<{ label: string; value: string; sub?: string }>).map(({ label, value, sub }) => (
          <View key={label} style={s.metricBox}>
            <Text style={s.metricValue}>{value}</Text>
            <Text style={s.metricLabel}>{label}</Text>
            {sub && <Text style={s.metricSub}>{sub}</Text>}
          </View>
        ))}
      </View>

      {/* Revenue by Channel */}
      <View style={s.section} wrap={false}>
        <Text style={s.sectionHeading}>Revenue by Channel</Text>
        <View style={s.table}>
          <View style={s.headerRow}>
            <Text style={[s.colHeader, { flex: 2 }]}>CHANNEL</Text>
            <Text style={[s.colHeader, { flex: 1.5, textAlign: "right" }]}>REVENUE</Text>
            <Text style={[s.colHeader, { flex: 1, textAlign: "right" }]}>SHARE</Text>
            <Text style={[s.colHeader, { flex: 1, textAlign: "right" }]}>CONV.</Text>
            <Text style={[s.colHeader, { flex: 1.5, textAlign: "right" }]}>AVG / CONV</Text>
            <Text style={[s.colHeader, { flex: 1, textAlign: "right" }]}>VS PRIOR</Text>
          </View>
          {ra.revenueByChannel.map((row, i) => (
            <View key={row.channelName} style={[s.tableRow, i % 2 !== 0 ? s.rowAlt : {}, row.channelName === "AI" ? s.rowAi : {}]}>
              <Text style={[s.cellText, { flex: 2 }]}>{row.channelName}</Text>
              <Text style={[s.cellBold, { flex: 1.5, textAlign: "right" }]}>{fmtUsd(row.revenue)}</Text>
              <Text style={[s.cellText, { flex: 1, textAlign: "right" }]}>{row.sharePercent}%</Text>
              <Text style={[s.cellText, { flex: 1, textAlign: "right" }]}>{row.conversions}</Text>
              <Text style={[s.cellText, { flex: 1.5, textAlign: "right" }]}>{fmtUsd(row.avgRevenuePerConversion)}</Text>
              <View style={{ flex: 1, alignItems: "flex-end" }}>
                {row.deltaVsPrior30d ? (
                  <Text style={row.deltaVsPrior30d.revenueDelta >= 0 ? s.deltaUp : s.deltaDown}>
                    {row.deltaVsPrior30d.revenueDelta >= 0 ? "+" : ""}{row.deltaVsPrior30d.revenueDeltaPercent}%
                  </Text>
                ) : (
                  <Text style={s.cellMuted}>—</Text>
                )}
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* AI Engine breakdown */}
      {ra.revenueByAiEngine.length > 0 && (
        <View style={s.section} wrap={false}>
          <Text style={s.sectionHeading}>Revenue by AI Engine</Text>
          <View style={s.engineGrid}>
            {ra.revenueByAiEngine.map((engine) => (
              <View key={engine.engineName} style={s.engineCard}>
                <Text style={s.engineName}>{engine.engineName}</Text>
                <Text style={s.engineRevenue}>{fmtUsd(engine.revenue)}</Text>
                <View style={s.engineRow}>
                  <Text style={s.engineLabel}>Share of AI revenue</Text>
                  <Text style={s.engineValue}>{engine.shareOfAiRevenuePercent}%</Text>
                </View>
                <View style={s.engineRow}>
                  <Text style={s.engineLabel}>Share of total</Text>
                  <Text style={s.engineValue}>{engine.shareOfTotalRevenuePercent}%</Text>
                </View>
                <View style={s.engineRow}>
                  <Text style={s.engineLabel}>Conversions</Text>
                  <Text style={s.engineValue}>{engine.conversions}</Text>
                </View>
                <View style={s.engineRow}>
                  <Text style={s.engineLabel}>Avg / conversion</Text>
                  <Text style={s.engineValue}>{fmtUsd(engine.avgRevenuePerConversion)}</Text>
                </View>
                {engine.highestRevenueLandingPage && (
                  <Text style={s.enginePage}>Top page: {urlPath(engine.highestRevenueLandingPage)}</Text>
                )}
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Top Revenue Pages */}
      {ra.topRevenuePages.length > 0 && (
        <View style={s.section} wrap={false}>
          <Text style={s.sectionHeading}>Top Revenue Pages</Text>
          <View style={s.table}>
            <View style={s.headerRow}>
              <Text style={[s.colHeader, { flex: 3 }]}>PAGE</Text>
              <Text style={[s.colHeader, { flex: 1.5, textAlign: "right" }]}>REVENUE</Text>
              <Text style={[s.colHeader, { flex: 1, textAlign: "right" }]}>SHARE</Text>
              <Text style={[s.colHeader, { flex: 1, textAlign: "right" }]}>CONV.</Text>
              <Text style={[s.colHeader, { flex: 1.5, textAlign: "right" }]}>AVG / CONV</Text>
            </View>
            {ra.topRevenuePages.map((page, i) => (
              <View key={page.pageUrl} style={[s.tableRow, i % 2 !== 0 ? s.rowAlt : {}]}>
                <Text style={[s.cellText, { flex: 3, fontFamily: "Courier" }]}>{urlPath(page.pageUrl)}</Text>
                <Text style={[s.cellBold, { flex: 1.5, textAlign: "right" }]}>{fmtUsd(page.revenue)}</Text>
                <Text style={[s.cellText, { flex: 1, textAlign: "right" }]}>{page.sharePercent}%</Text>
                <Text style={[s.cellText, { flex: 1, textAlign: "right" }]}>{page.conversions}</Text>
                <Text style={[s.cellText, { flex: 1.5, textAlign: "right" }]}>{fmtUsd(page.avgRevenuePerConversion)}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Insights */}
      {ra.insights.length > 0 && (
        <View style={s.section}>
          <Text style={s.sectionHeading}>Revenue Insights</Text>
          {ra.insights.map((ins, i) => (
            <View key={i} style={s.insightBlock} wrap={false}>
              <Text style={s.insightText}>{ins.insight}</Text>
              <Text style={s.insightMetric}>{ins.supportingMetric}</Text>
              <Text style={s.insightImplication}>{ins.businessImplication}</Text>
            </View>
          ))}
        </View>
      )}

      {/* Patent relevance */}
      <Text style={s.patent}>{ra.patentRelevance}</Text>

      {/* Future capabilities */}
      <View style={s.futureBox} wrap={false}>
        <Text style={s.futureTitle}>COMING SOON</Text>
        <Text style={s.futureText}>{ra.futureCapabilities.cacNote}</Text>
        <Text style={s.futureText}>{ra.futureCapabilities.ltvNote}</Text>
      </View>
    </>
  );
}

// ─── Main export ──────────────────────────────────────────────────────────────

export function RevenueAttributionPage({
  revenueAttribution,
}: {
  revenueAttribution: RevenueAttribution;
}) {
  return (
    <>
      <Text style={s.heading}>Revenue Attribution</Text>
      <Text style={s.subheading}>Where your revenue actually comes from, measured by the meSEO Site Tag</Text>
      <FullRevenueContent ra={revenueAttribution} />
    </>
  );
}
