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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, color: C.muted, marginBottom: 16 },
  sectionLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 8 },
  // Cross-device callout
  cdBox: { backgroundColor: "#f5f3ff", borderRadius: 4, padding: 10, marginBottom: 16, borderWidth: 0.75, borderColor: "#ddd6fe" },
  cdText: { fontSize: 9, color: "#5b21b6", lineHeight: 1.5 },
  // Distribution bars
  distGrid: { marginBottom: 16 },
  distRow: { flexDirection: "row", alignItems: "center", marginBottom: 7, gap: 8 },
  distLabel: { fontSize: 8.5, color: C.body, width: 80 },
  distBarBg: { flex: 1, height: 7, backgroundColor: C.surface, borderRadius: 3, overflow: "hidden" },
  distBarFill: { height: 7, borderRadius: 3 },
  distCount: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, width: 60, textAlign: "right" },
  // Path cards
  pathCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8, marginBottom: 7 },
  pathDesc: { fontSize: 8.5, color: C.ink, marginBottom: 5 },
  stepRow: { flexDirection: "row", flexWrap: "wrap", gap: 3, marginBottom: 5 },
  stepPill: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 2, borderWidth: 0.5 },
  stepPillText: { fontSize: 7, fontFamily: "Helvetica-Bold" },
  pathMeta: { flexDirection: "row", gap: 12 },
  pathMetaText: { fontSize: 7.5, color: C.muted },
  // Two-column grid
  twoCol: { flexDirection: "row", gap: 12, marginTop: 4 },
  col: { flex: 1 },
  colCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8 },
  colLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.7, textTransform: "uppercase", marginBottom: 7 },
  channelRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 5 },
  channelName: { fontSize: 8.5, color: C.body, flex: 1 },
  channelCounts: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink },
  triggerRow: { flexDirection: "row", gap: 5, marginBottom: 5 },
  triggerIdx: { fontSize: 7.5, color: C.muted, width: 10 },
  triggerPath: { fontSize: 8, color: C.body, flex: 1 },
  triggerMeta: { fontSize: 7.5, color: C.muted },
});

const STEP_COLORS: Record<string, { bg: string; border: string; text: string }> = {
  ai_engine: { bg: "#f5f3ff", border: "#ddd6fe", text: "#5b21b6" },
  page: { bg: "#f8fafc", border: "#e2e8f0", text: "#475569" },
  conversion: { bg: "#f0fdf4", border: "#bbf7d0", text: "#166534" },
};

function urlPath(url: string): string {
  try { return new URL(url).pathname || "/"; } catch { return url.slice(0, 30); }
}

interface Props {
  multiTouchAiPath: MultiTouchAiPath;
}

export function MultiTouchAiPathPage({ multiTouchAiPath }: Props) {
  const { topConversionPaths, pathComplexityDistribution, topEntryChannels, topConversionTriggers, crossDeviceJourneys } = multiTouchAiPath;
  const dist = pathComplexityDistribution;
  const totalForRate = dist.singleTouch.count + dist.twoTouch.count + dist.multiTouch.count;
  const maxCount = Math.max(dist.singleTouch.count, dist.twoTouch.count, dist.multiTouch.count, 1);

  return (
    <View>
      <Text style={s.heading}>Multi-Touch AI Path Analysis</Text>
      <Text style={s.subheading}>First-party visitor journey reconstruction from AI engine referral through conversion.</Text>

      {/* Cross-device callout */}
      {crossDeviceJourneys.detected > 0 && (
        <View style={s.cdBox}>
          <Text style={s.cdText}>
            {crossDeviceJourneys.detected} cross-device journeys detected ({crossDeviceJourneys.percentOfConversions}% of AI conversions).
            {" "}{crossDeviceJourneys.typicalPattern}
          </Text>
        </View>
      )}

      {/* Path complexity distribution */}
      <Text style={s.sectionLabel}>Path Complexity Distribution</Text>
      <View style={s.distGrid} wrap={false}>
        {[
          { label: "Single-touch", count: dist.singleTouch.count, percent: dist.singleTouch.percent, color: "#34d399" },
          { label: "Two-touch", count: dist.twoTouch.count, percent: dist.twoTouch.percent, color: "#60a5fa" },
          { label: "Multi-touch (3+)", count: dist.multiTouch.count, percent: dist.multiTouch.percent, color: "#a78bfa" },
        ].map((row) => (
          <View key={row.label} style={s.distRow}>
            <Text style={s.distLabel}>{row.label}</Text>
            <View style={s.distBarBg}>
              <View style={[s.distBarFill, { width: `${(row.count / maxCount) * 100}%`, backgroundColor: row.color }]} />
            </View>
            <Text style={s.distCount}>{row.count} ({row.percent}%)</Text>
          </View>
        ))}
        {totalForRate > 0 && dist.singleTouch.avgConversionRate > 0 && (
          <Text style={{ ...s.subheading, marginTop: 2, marginBottom: 0 }}>
            Overall AI conversion rate: {dist.singleTouch.avgConversionRate}%
          </Text>
        )}
      </View>

      {/* Top conversion paths */}
      {topConversionPaths.length > 0 && (
        <View wrap={false}>
          <Text style={[s.sectionLabel, { marginTop: 8 }]}>Top Conversion Paths</Text>
          {topConversionPaths.slice(0, 4).map((path, i) => {
            return (
              <View key={i} style={s.pathCard}>
                <View style={s.stepRow}>
                  {path.pathSteps.map((step, j) => {
                    const colors = STEP_COLORS[step.stepType] ?? STEP_COLORS.page;
                    const label = step.identifier.length > 22 ? step.identifier.slice(0, 22) + "…" : step.identifier;
                    return (
                      <View key={j} style={{ flexDirection: "row", alignItems: "center", gap: 2 }}>
                        {j > 0 && <Text style={{ fontSize: 7, color: C.muted }}>→</Text>}
                        <View style={[s.stepPill, { backgroundColor: colors.bg, borderColor: colors.border }]}>
                          <Text style={[s.stepPillText, { color: colors.text }]}>{label}</Text>
                        </View>
                      </View>
                    );
                  })}
                </View>
                <View style={s.pathMeta}>
                  <Text style={s.pathMetaText}>{path.conversionCount} conversions</Text>
                  {path.avgTimeToConversion > 0 && (
                    <Text style={s.pathMetaText}>
                      avg {path.avgTimeToConversion < 60 ? `${path.avgTimeToConversion}s` : `${Math.round(path.avgTimeToConversion / 60)}m`} to convert
                    </Text>
                  )}
                  {path.crossDevice && <Text style={[s.pathMetaText, { color: "#7c3aed" }]}>cross-device</Text>}
                </View>
              </View>
            );
          })}
        </View>
      )}

      {/* Entry channels + conversion triggers */}
      <View style={s.twoCol} wrap={false}>
        {topEntryChannels.length > 0 && (
          <View style={s.col}>
            <View style={s.colCard}>
              <Text style={s.colLabel}>AI Entry Channels</Text>
              {topEntryChannels.slice(0, 5).map((ch, i) => (
                <View key={i} style={s.channelRow}>
                  <Text style={s.channelName}>{ch.channel}</Text>
                  <Text style={s.channelCounts}>{ch.conversionsAsFirstTouch} / {ch.conversionsAsLastTouch}</Text>
                </View>
              ))}
              <Text style={[s.triggerMeta, { marginTop: 4 }]}>First-touch / last-touch</Text>
            </View>
          </View>
        )}

        {topConversionTriggers.length > 0 && (
          <View style={s.col}>
            <View style={s.colCard}>
              <Text style={s.colLabel}>Conversion Triggers</Text>
              {topConversionTriggers.slice(0, 5).map((trig, i) => (
                <View key={i} style={s.triggerRow}>
                  <Text style={s.triggerIdx}>{i + 1}.</Text>
                  <View style={{ flex: 1 }}>
                    <Text style={s.triggerPath}>{urlPath(trig.pageUrl)}</Text>
                    <Text style={s.triggerMeta}>{trig.conversionCount} conv{trig.avgPriorPageviews > 0 ? ` · ${trig.avgPriorPageviews} prior pages` : ""}</Text>
                  </View>
                </View>
              ))}
            </View>
          </View>
        )}
      </View>
    </View>
  );
}
