import { View, Text, StyleSheet } from "@react-pdf/renderer";
import { C, S } from "../styles";
import type { BehavioralActionBridge } 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 },
  // Patterns
  patternGrid: { flexDirection: "row", flexWrap: "wrap", marginHorizontal: -4, marginBottom: 16 },
  patternCard: { width: "31%", marginHorizontal: "1%", marginBottom: 8, borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8 },
  patternTitle: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 4, lineHeight: 1.3 },
  patternImpact: { fontSize: 8, color: C.body, lineHeight: 1.4 },
  // Enhanced actions
  actionBlock: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, marginBottom: 10, overflow: "hidden" },
  actionHeader: { backgroundColor: C.surface, paddingHorizontal: 10, paddingVertical: 8, borderBottomWidth: 0.5, borderBottomColor: C.border, flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start" },
  actionTitle: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink, flex: 1, lineHeight: 1.3 },
  confBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 2 },
  confBadgeText: { fontSize: 7, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  actionBody: { paddingHorizontal: 10, paddingVertical: 8, gap: 6 },
  rewrittenText: { fontSize: 8.5, color: C.body, lineHeight: 1.5 },
  // Impact grid
  impactGrid: { flexDirection: "row", gap: 8, backgroundColor: "#f8fafc", borderRadius: 3, padding: 7 },
  impactCol: { flex: 1 },
  impactLabel: { fontSize: 7, color: C.muted, marginBottom: 2 },
  impactValue: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink },
  impactProjected: { fontSize: 9, fontFamily: "Helvetica-Bold", color: "#059669" },
  // Evidence
  evidenceLabel: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.6, marginTop: 4, marginBottom: 3 },
  evidenceRow: { flexDirection: "row", alignItems: "flex-start", gap: 5, marginBottom: 3 },
  evidenceBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  evidenceBadgeText: { fontSize: 6.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.4 },
  evidenceText: { fontSize: 7.5, color: C.body, lineHeight: 1.4, flex: 1 },
  // New findings
  findingCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, marginBottom: 8, padding: 8 },
  findingHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 6 },
  findingTitle: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink, flex: 1, lineHeight: 1.3 },
  sevBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 2, marginLeft: 8 },
  sevBadgeText: { fontSize: 7, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  findingDesc: { fontSize: 8.5, color: C.body, lineHeight: 1.5, marginBottom: 6 },
  evidenceDot: { width: 4, height: 4, borderRadius: 2, backgroundColor: C.muted, marginTop: 3 },
  findingEv: { fontSize: 7.5, color: C.body, lineHeight: 1.4, flex: 1 },
  findingRec: { fontSize: 8, color: C.accent, lineHeight: 1.4, marginTop: 6, paddingTop: 6, borderTopWidth: 0.5, borderTopColor: C.border },
});

const SEV_COLORS: Record<string, { bg: string; text: string }> = {
  critical: { bg: "#fee2e2", text: "#991b1b" },
  high: { bg: "#ffedd5", text: "#9a3412" },
  moderate: { bg: "#fef3c7", text: "#92400e" },
  low: { bg: "#f1f5f9", text: "#475569" },
};

const CONF_COLORS: Record<string, { bg: string; text: string }> = {
  high: { bg: "#d1fae5", text: "#065f46" },
  moderate: { bg: "#fef3c7", text: "#92400e" },
  low: { bg: "#f1f5f9", text: "#475569" },
};

const SRC_COLORS: Record<string, { bg: string; text: string }> = {
  "signal-center": { bg: "#ede9fe", text: "#5b21b6" },
  "page-strategic-pass": { bg: "#dbeafe", text: "#1e40af" },
  "ai-attribution": { bg: "#d1fae5", text: "#065f46" },
};

const SRC_LABELS: Record<string, string> = {
  "signal-center": "Behavioral Telemetry",
  "page-strategic-pass": "Page Review",
  "ai-attribution": "AI Attribution",
};

function fmt(n: number): string {
  return n % 1 === 0 ? n.toLocaleString() : n.toFixed(1);
}

interface Props {
  behavioralActionBridge: BehavioralActionBridge;
}

export function BehavioralActionBridgePage({ behavioralActionBridge }: Props) {
  const { enhancedActions, newBehavioralFindings, topBehavioralPatterns } = behavioralActionBridge;

  return (
    <View>
      <Text style={s.heading}>Behavioral Intelligence: Quantified Action Bridge</Text>
      <Text style={s.subheading}>First-party behavioral telemetry cross-referenced with priority recommendations</Text>

      {/* Behavioral Patterns */}
      {topBehavioralPatterns.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>Behavioral Patterns Detected</Text>
          <View style={s.patternGrid}>
            {topBehavioralPatterns.map((pattern, i) => (
              <View key={i} style={s.patternCard} wrap={false}>
                <Text style={s.patternTitle}>{pattern.pattern}</Text>
                <Text style={s.patternImpact}>{pattern.impact}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Enhanced Actions */}
      {enhancedActions.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>Actions Enhanced with Behavioral Evidence</Text>
          {enhancedActions.map((action, i) => {
            const conf = CONF_COLORS[action.quantifiedImpactEstimate.confidence] ?? CONF_COLORS.moderate;
            return (
              <View key={i} style={s.actionBlock} wrap={false}>
                <View style={s.actionHeader}>
                  <Text style={s.actionTitle}>{action.originalActionTitle}</Text>
                  <View style={[s.confBadge, { backgroundColor: conf.bg }]}>
                    <Text style={[s.confBadgeText, { color: conf.text }]}>
                      {action.quantifiedImpactEstimate.confidence.toUpperCase()}
                    </Text>
                  </View>
                </View>
                <View style={s.actionBody}>
                  <Text style={s.rewrittenText}>{action.rewrittenActionDescription}</Text>
                  {/* Impact */}
                  <View style={s.impactGrid}>
                    <View style={s.impactCol}>
                      <Text style={s.impactLabel}>Metric</Text>
                      <Text style={s.impactValue}>{action.quantifiedImpactEstimate.metric}</Text>
                    </View>
                    <View style={s.impactCol}>
                      <Text style={s.impactLabel}>Current</Text>
                      <Text style={s.impactValue}>{fmt(action.quantifiedImpactEstimate.currentValue)}</Text>
                    </View>
                    <View style={s.impactCol}>
                      <Text style={s.impactLabel}>Projected</Text>
                      <Text style={s.impactProjected}>{fmt(action.quantifiedImpactEstimate.projectedValue)}</Text>
                    </View>
                  </View>
                  {/* Evidence */}
                  {action.behavioralEvidence.length > 0 && (
                    <View>
                      <Text style={s.evidenceLabel}>SUPPORTING EVIDENCE</Text>
                      {action.behavioralEvidence.map((ev, j) => {
                        const src = SRC_COLORS[ev.source] ?? SRC_COLORS["signal-center"];
                        return (
                          <View key={j} style={s.evidenceRow}>
                            <View style={[s.evidenceBadge, { backgroundColor: src.bg }]}>
                              <Text style={[s.evidenceBadgeText, { color: src.text }]}>
                                {SRC_LABELS[ev.source] ?? ev.source}
                              </Text>
                            </View>
                            <Text style={s.evidenceText}>{ev.signal}</Text>
                          </View>
                        );
                      })}
                    </View>
                  )}
                </View>
              </View>
            );
          })}
        </View>
      )}

      {/* New Behavioral Findings */}
      {newBehavioralFindings.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>New Findings from Behavioral Analysis</Text>
          {newBehavioralFindings.map((finding, i) => {
            const sev = SEV_COLORS[finding.severity] ?? SEV_COLORS.moderate;
            return (
              <View key={i} style={s.findingCard} wrap={false}>
                <View style={s.findingHeader}>
                  <Text style={s.findingTitle}>{finding.title}</Text>
                  <View style={[s.sevBadge, { backgroundColor: sev.bg }]}>
                    <Text style={[s.sevBadgeText, { color: sev.text }]}>
                      {finding.severity.toUpperCase()}
                    </Text>
                  </View>
                </View>
                <Text style={s.findingDesc}>{finding.description}</Text>
                {finding.behavioralEvidence.map((ev, j) => (
                  <View key={j} style={s.evidenceRow}>
                    <View style={s.evidenceDot} />
                    <Text style={s.findingEv}>{ev}</Text>
                  </View>
                ))}
                <Text style={s.findingRec}>{finding.recommendation}</Text>
              </View>
            );
          })}
        </View>
      )}
    </View>
  );
}
