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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, marginBottom: 16, color: C.muted },
  // 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 },
  // Distribution bars
  distRow: { flexDirection: "row", alignItems: "center", gap: 6, marginBottom: 4 },
  distLabel: { width: 50, fontSize: 7.5, color: C.body },
  distBarBg: { flex: 1, height: 6, backgroundColor: "#f1f5f9", borderRadius: 3 },
  distBarFill: { height: 6, borderRadius: 3 },
  distCount: { width: 40, fontSize: 7, color: C.muted, textAlign: "right" },
  distConv: { width: 40, fontSize: 7, color: C.muted, textAlign: "right" },
  // 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" },
  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 },
  cellMono: { fontSize: 7.5, fontFamily: "Courier", color: C.body },
  cellScore: { fontSize: 8, fontFamily: "Helvetica-Bold" },
  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: "#c7d2fe", borderRadius: 4, padding: 8, backgroundColor: "#eef2ff" },
  engineName: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 4 },
  engineScore: { fontSize: 13, fontFamily: "Helvetica-Bold", color: "#4f46e5", marginBottom: 4 },
  engineSessions: { fontSize: 7, color: C.muted },
  // 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" },
  // Patent
  patent: { fontSize: 7.5, color: C.muted, fontStyle: "italic", marginBottom: 0 },
  // Boost badge
  boost: { fontSize: 8, fontFamily: "Helvetica-Bold", color: "#059669" },
});

const BAND_COLORS: Record<ScoreBand, string> = {
  very_high: "#8b5cf6",
  high:      "#10b981",
  moderate:  "#f59e0b",
  low:       "#94a3b8",
  very_low:  "#cbd5e1",
};

const BAND_LABELS: Record<ScoreBand, string> = {
  very_high: "Very High (81–100)",
  high:      "High (61–80)",
  moderate:  "Moderate (41–60)",
  low:       "Low (21–40)",
  very_low:  "Very Low (0–20)",
};

const BAND_ORDER: ScoreBand[] = ["very_high", "high", "moderate", "low", "very_low"];

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;
}

export function PredictiveConversionScoringPage({
  predictiveConversionScoring: pcs,
}: {
  predictiveConversionScoring: PredictiveConversionScoring;
}) {
  const totalSessions = pcs.totalScoredSessions;
  const highIntentCount = pcs.scoreDistribution.high + pcs.scoreDistribution.very_high;
  const highIntentPct = totalSessions > 0 ? Math.round((highIntentCount / totalSessions) * 100) : 0;

  return (
    <>
      <Text style={s.heading}>Predictive Conversion Scoring</Text>
      <Text style={s.subheading}>
        Real-time behavioral intent scoring for active sessions — last {pcs.windowDays} days
      </Text>

      {/* Aggregate metrics */}
      <View style={s.metricsRow} wrap={false}>
        {([
          { label: "Sessions Scored", value: totalSessions.toLocaleString() },
          { label: "Avg Score", value: `${pcs.avgScore}/100` },
          { label: "High-Intent Sessions", value: highIntentCount.toLocaleString(), sub: `${highIntentPct}% of total` },
          { label: "Active (Last 30 min)", value: pcs.liveSessionsSnapshot.activeLast30Min.toLocaleString(), sub: `${pcs.liveSessionsSnapshot.highIntentCount} high-intent` },
        ] 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>

      {/* Score distribution */}
      <View style={s.section} wrap={false}>
        <Text style={s.sectionHeading}>Score Distribution</Text>
        {BAND_ORDER.map((band) => {
          const count = pcs.scoreDistribution[band] ?? 0;
          const pct = totalSessions > 0 ? Math.round((count / totalSessions) * 100) : 0;
          const convRate = pcs.conversionRateByBand[band];
          return (
            <View key={band} style={s.distRow}>
              <Text style={s.distLabel}>{BAND_LABELS[band].split(" (")[0]}</Text>
              <View style={s.distBarBg}>
                <View style={[s.distBarFill, { width: `${pct}%`, backgroundColor: BAND_COLORS[band] }]} />
              </View>
              <Text style={s.distCount}>{count.toLocaleString()} ({pct}%)</Text>
              {convRate != null
                ? <Text style={s.distConv}>{convRate}% conv.</Text>
                : <Text style={s.distConv}>—</Text>
              }
            </View>
          );
        })}
      </View>

      {/* Score by channel */}
      {pcs.scoreByChannel.length > 0 && (
        <View style={s.section} wrap={false}>
          <Text style={s.sectionHeading}>Intent Score 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" }]}>AVG SCORE</Text>
              <Text style={[s.colHeader, { flex: 1, textAlign: "right" }]}>SESSIONS</Text>
              <Text style={[s.colHeader, { flex: 1.5, textAlign: "right" }]}>TOP BAND</Text>
            </View>
            {pcs.scoreByChannel.map((ch, i) => (
              <View key={ch.channelName} style={[s.tableRow, i % 2 !== 0 ? s.rowAlt : {}]}>
                <Text style={[s.cellText, { flex: 2 }]}>{ch.channelName}</Text>
                <Text style={[s.cellScore, { flex: 1.5, textAlign: "right", color: BAND_COLORS[ch.topBand] }]}>
                  {ch.avgScore}/100
                </Text>
                <Text style={[s.cellText, { flex: 1, textAlign: "right" }]}>{ch.sessionCount.toLocaleString()}</Text>
                <Text style={[s.cellMuted, { flex: 1.5, textAlign: "right" }]}>{BAND_LABELS[ch.topBand].split(" (")[0]}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* AI engine cards */}
      {pcs.scoreByAiEngine.length > 0 && (
        <View style={s.section} wrap={false}>
          <Text style={s.sectionHeading}>Intent Score by AI Engine</Text>
          <View style={s.engineGrid}>
            {pcs.scoreByAiEngine.map((engine) => (
              <View key={engine.engineName} style={s.engineCard}>
                <Text style={s.engineName}>{engine.engineName}</Text>
                <Text style={s.engineScore}>{engine.avgScore}/100</Text>
                <Text style={s.engineSessions}>{engine.sessionCount.toLocaleString()} sessions</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Top intent-boosting pages */}
      {pcs.topScoringPages.length > 0 && (
        <View style={s.section} wrap={false}>
          <Text style={s.sectionHeading}>Top Intent-Boosting 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" }]}>AVG BOOST</Text>
              <Text style={[s.colHeader, { flex: 1.5, textAlign: "right" }]}>HIGH-INTENT VISITS</Text>
            </View>
            {pcs.topScoringPages.slice(0, 10).map((page, i) => (
              <View key={page.pageUrl} style={[s.tableRow, i % 2 !== 0 ? s.rowAlt : {}]}>
                <Text style={[s.cellMono, { flex: 3 }]}>{urlPath(page.pageUrl)}</Text>
                <Text style={[s.boost, { flex: 1.5, textAlign: "right" }]}>+{page.avgScoreBoost} pts</Text>
                <Text style={[s.cellText, { flex: 1.5, textAlign: "right" }]}>{page.visitCount.toLocaleString()}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Insights */}
      {pcs.insights.length > 0 && (
        <View style={s.section}>
          <Text style={s.sectionHeading}>Scoring Insights</Text>
          {pcs.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}>{pcs.patentRelevance}</Text>
    </>
  );
}
