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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, color: C.muted, marginBottom: 14 },
  // Gap magnitude pill
  pill: { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2, alignSelf: "flex-start", marginBottom: 12 },
  pillText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.8 },
  // Narrative callout
  narrativeBox: { backgroundColor: C.surface, borderRadius: 4, padding: 10, marginBottom: 16 },
  narrativeText: { fontSize: 9.5, color: C.body, lineHeight: 1.5 },
  // Section label
  sectionLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 8 },
  // Dimension grid: two columns
  dimGrid: { flexDirection: "row", flexWrap: "wrap", marginHorizontal: -4, marginBottom: 16 },
  dimCard: { width: "48%", marginHorizontal: "1%", marginBottom: 8, borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8 },
  dimTitle: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 4 },
  dirBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5, alignSelf: "flex-start", marginBottom: 6 },
  dirBadgeText: { fontSize: 7, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  dimRow: { flexDirection: "row", marginBottom: 5, gap: 8 },
  dimCol: { flex: 1 },
  dimLabel: { fontSize: 7.5, color: C.muted, marginBottom: 1.5 },
  dimValue: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink },
  dimSub: { fontSize: 7, color: C.muted, marginTop: 1.5 },
  deltaRow: { flexDirection: "row", alignItems: "center", gap: 4, marginTop: 4, marginBottom: 4 },
  deltaText: { fontSize: 10, fontFamily: "Helvetica-Bold" },
  deltaLabel: { fontSize: 7.5, color: C.muted },
  dimExplanation: { fontSize: 8, color: C.body, lineHeight: 1.4 },
  // Insights
  insightBox: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, overflow: "hidden", marginBottom: 16 },
  insightRow: { paddingHorizontal: 10, paddingVertical: 7, borderBottomWidth: 0.5, borderBottomColor: "#f1f5f9" },
  insightText: { fontSize: 9, color: C.body, lineHeight: 1.4, marginBottom: 3 },
  insightSub: { fontSize: 7.5, color: C.muted, lineHeight: 1.3 },
  // Why this matters callout
  calloutBox: { backgroundColor: "#f3f0ff", borderRadius: 4, padding: 10, marginTop: 4 },
  calloutLabel: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: "#7c3aed", letterSpacing: 0.8, marginBottom: 4 },
  calloutText: { fontSize: 9, color: C.body, lineHeight: 1.5 },
});

const GAP_COLORS: Record<string, { bg: string; text: string }> = {
  minimal: { bg: "#d1fae5", text: "#065f46" },
  moderate: { bg: "#fef3c7", text: "#92400e" },
  significant: { bg: "#fee2e2", text: "#991b1b" },
};

const DIR_COLORS: Record<string, { bg: string; text: string }> = {
  predicted_overestimated: { bg: "#fee2e2", text: "#991b1b" },
  predicted_underestimated: { bg: "#d1fae5", text: "#065f46" },
  aligned: { bg: "#f1f5f9", text: "#475569" },
};

const DIR_LABELS: Record<string, string> = {
  predicted_overestimated: "Over-predicted",
  predicted_underestimated: "Under-predicted",
  aligned: "Aligned",
};

function formatValue(v: number | string): string {
  if (typeof v === "number") {
    return Number.isInteger(v) ? v.toLocaleString() : `${v.toFixed(1)}%`;
  }
  return v;
}

interface Props {
  aiSourceAttributionComparison: AiSourceAttributionComparison;
}

export function AiSourceAttributionComparisonPage({ aiSourceAttributionComparison }: Props) {
  const { predictionVsActual, topInsights, overallGapMagnitude, overallGapNarrative, comparisonWindow } = aiSourceAttributionComparison;
  const gapColor = GAP_COLORS[overallGapMagnitude] ?? GAP_COLORS.moderate;
  const GAP_LABEL: Record<string, string> = {
    minimal: "MINIMAL GAP",
    moderate: "MODERATE GAP",
    significant: "SIGNIFICANT GAP",
  };

  return (
    <View>
      <Text style={s.heading}>Public Signal Prediction vs First-Party Measurement</Text>
      <Text style={s.subheading}>{comparisonWindow.daysCovered}-day comparison window</Text>

      {/* Gap magnitude pill */}
      <View style={[s.pill, { backgroundColor: gapColor.bg }]}>
        <Text style={[s.pillText, { color: gapColor.text }]}>
          {GAP_LABEL[overallGapMagnitude] ?? "GAP ANALYSIS"}
        </Text>
      </View>

      {/* Narrative */}
      <View style={s.narrativeBox}>
        <Text style={s.narrativeText}>{overallGapNarrative}</Text>
      </View>

      {/* Dimension grid */}
      {predictionVsActual.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>Dimension-by-Dimension Comparison</Text>
          <View style={s.dimGrid}>
            {predictionVsActual.map((dim, i) => {
              const dirColor = DIR_COLORS[dim.deltaDirection] ?? DIR_COLORS.aligned;
              const deltaSign = dim.deltaPercent >= 0 ? "+" : "";
              return (
                <View key={i} style={s.dimCard} wrap={false}>
                  <Text style={s.dimTitle}>{dim.dimension}</Text>
                  <View style={[s.dirBadge, { backgroundColor: dirColor.bg }]}>
                    <Text style={[s.dirBadgeText, { color: dirColor.text }]}>
                      {DIR_LABELS[dim.deltaDirection] ?? dim.deltaDirection}
                    </Text>
                  </View>
                  <View style={s.dimRow}>
                    <View style={s.dimCol}>
                      <Text style={s.dimLabel}>Predicted</Text>
                      <Text style={s.dimValue}>{formatValue(dim.publicSignalPrediction.value)}</Text>
                      <Text style={s.dimSub}>{dim.publicSignalPrediction.confidence} confidence</Text>
                    </View>
                    <View style={s.dimCol}>
                      <Text style={s.dimLabel}>Actual (first-party)</Text>
                      <Text style={s.dimValue}>{formatValue(dim.firstPartyActual.value)}</Text>
                      <Text style={s.dimSub}>n={dim.firstPartyActual.sampleSize.toLocaleString()}</Text>
                    </View>
                  </View>
                  <View style={s.deltaRow}>
                    <Text style={[s.deltaText, { color: dirColor.text }]}>
                      {deltaSign}{dim.deltaPercent.toFixed(1)}%
                    </Text>
                    <Text style={s.deltaLabel}>delta</Text>
                  </View>
                  <Text style={s.dimExplanation}>{dim.explanation}</Text>
                </View>
              );
            })}
          </View>
        </View>
      )}

      {/* Insights */}
      {topInsights.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>Key Insights</Text>
          <View style={s.insightBox}>
            {topInsights.map((insight, i) => (
              <View key={i} style={s.insightRow}>
                <Text style={s.insightText}>{insight.insight}</Text>
                <Text style={s.insightSub}>{insight.patentRelevance}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Why this matters */}
      <View style={s.calloutBox}>
        <Text style={s.calloutLabel}>WHY THIS MATTERS</Text>
        <Text style={s.calloutText}>
          Public signal analysis can only estimate AI referral behavior from what is observable in search results. First-party Site Tag data measures what actually happens. The gap between prediction and measurement is where optimization opportunity lives.
        </Text>
      </View>
    </View>
  );
}
