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

const ENGINE_COLORS: Record<string, string> = {
  chatgpt: "#10b981",
  perplexity: "#06b6d4",
  claude: "#7c3aed",
  gemini: "#2563eb",
  copilot: "#0ea5e9",
};

const SENSITIVITY_COLOR: Record<string, string> = {
  high: C.red,
  medium: C.amber,
  low: C.green,
};

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subtext: { ...S.small, marginBottom: 14 },
  engineCard: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    marginBottom: 10,
    overflow: "hidden",
    backgroundColor: C.white,
  },
  cardHeader: {
    flexDirection: "row",
    alignItems: "center",
    gap: 7,
    paddingHorizontal: 10,
    paddingVertical: 8,
    backgroundColor: C.surface,
    borderBottomWidth: 0.5,
    borderBottomColor: C.border,
  },
  engineDot: { width: 7, height: 7, borderRadius: 3.5 },
  engineName: { fontSize: 10.5, fontFamily: "Helvetica-Bold", color: C.ink },
  parentCo: { fontSize: 8, color: C.muted, marginLeft: 4 },
  topBadge: {
    paddingHorizontal: 5,
    paddingVertical: 1.5,
    borderRadius: 2,
    backgroundColor: "#1e293b",
    fontSize: 6.5,
    fontFamily: "Helvetica-Bold",
    color: "#94a3b8",
    letterSpacing: 0.4,
  },
  citationText: { fontSize: 7.5, color: C.muted, flex: 1, lineHeight: 1.4, marginTop: 2 },
  overlayRow: {
    flexDirection: "row",
    gap: 10,
    paddingHorizontal: 10,
    paddingVertical: 7,
    borderBottomWidth: 0.5,
    borderBottomColor: C.border,
    backgroundColor: "#fafbfc",
  },
  overlayStat: { alignItems: "center" },
  overlayLabel: { fontSize: 7, color: C.muted, letterSpacing: 0.3 },
  overlayValue: { fontSize: 12, fontFamily: "Helvetica-Bold", color: C.ink, marginTop: 1 },
  signalsRow: {
    flexDirection: "row",
    gap: 12,
    paddingHorizontal: 10,
    paddingVertical: 7,
    borderBottomWidth: 0.5,
    borderBottomColor: C.border,
  },
  signalBlock: {},
  signalLabel: { ...S.label, fontSize: 6.5, marginBottom: 3 },
  pill: {
    paddingHorizontal: 5,
    paddingVertical: 2,
    borderRadius: 2,
    fontSize: 7,
    fontFamily: "Helvetica-Bold",
    color: C.white,
  },
  schemaChips: { flexDirection: "row", gap: 4, flexWrap: "wrap" },
  schemaChip: {
    paddingHorizontal: 4,
    paddingVertical: 1.5,
    borderRadius: 2,
    backgroundColor: C.surface,
    borderWidth: 0.5,
    borderColor: C.border,
    fontSize: 7,
    color: C.muted,
  },
  approachBlock: { paddingHorizontal: 10, paddingVertical: 8 },
  approachLabel: { ...S.label, fontSize: 6.5, marginBottom: 4 },
  approachTip: { flexDirection: "row", alignItems: "flex-start", gap: 5, marginBottom: 4 },
  tipDot: { width: 4, height: 4, borderRadius: 2, marginTop: 2 },
  tipText: { fontSize: 7.5, color: C.muted, flex: 1, lineHeight: 1.4 },
});

function EngineCard({ card, isTop }: { card: EnginePersonalityCard; isTop: boolean }) {
  const dotColor = ENGINE_COLORS[card.engineId] ?? C.muted;

  return (
    <View style={s.engineCard} wrap={false}>
      <View style={s.cardHeader}>
        <View style={[s.engineDot, { backgroundColor: dotColor }]} />
        <Text style={s.engineName}>{card.displayName}</Text>
        <Text style={s.parentCo}>{card.parentCompany}</Text>
        {isTop && <Text style={s.topBadge}>TOP SOURCE</Text>}
        <Text style={[s.citationText, { marginLeft: 4 }]}>{card.citationStyle.slice(0, 120)}</Text>
      </View>

      {card.firstPartyOverlay && (
        <View style={s.overlayRow}>
          <View style={s.overlayStat}>
            <Text style={s.overlayLabel}>AI SESSIONS (30D)</Text>
            <Text style={s.overlayValue}>{card.firstPartyOverlay.sessions30d.toLocaleString()}</Text>
          </View>
          <View style={s.overlayStat}>
            <Text style={s.overlayLabel}>CONVERSIONS</Text>
            <Text style={s.overlayValue}>{card.firstPartyOverlay.conversions30d}</Text>
          </View>
          {card.firstPartyOverlay.conversionRate != null && (
            <View style={s.overlayStat}>
              <Text style={s.overlayLabel}>CONV. RATE</Text>
              <Text style={s.overlayValue}>{card.firstPartyOverlay.conversionRate}%</Text>
            </View>
          )}
        </View>
      )}

      <View style={s.signalsRow}>
        <View style={s.signalBlock}>
          <Text style={s.signalLabel}>E-E-A-T SENSITIVITY</Text>
          <Text style={[s.pill, { backgroundColor: SENSITIVITY_COLOR[card.eAtSensitivity] ?? C.muted }]}>
            {card.eAtSensitivity.toUpperCase()}
          </Text>
        </View>
        <View style={s.signalBlock}>
          <Text style={s.signalLabel}>RECENCY BIAS</Text>
          <Text style={[s.pill, { backgroundColor: SENSITIVITY_COLOR[card.recencyBias] ?? C.muted }]}>
            {card.recencyBias.toUpperCase()}
          </Text>
        </View>
        <View style={s.signalBlock}>
          <Text style={s.signalLabel}>SCHEMA PRIORITIES</Text>
          <View style={s.schemaChips}>
            {card.schemaPriorities.slice(0, 4).map((sc) => (
              <Text key={sc} style={s.schemaChip}>{sc}</Text>
            ))}
          </View>
        </View>
      </View>

      <View style={s.approachBlock}>
        <Text style={s.approachLabel}>OPTIMIZATION APPROACH</Text>
        {card.optimizationApproach.map((tip, i) => (
          <View key={i} style={s.approachTip}>
            <View style={[s.tipDot, { backgroundColor: dotColor }]} />
            <Text style={s.tipText}>{tip}</Text>
          </View>
        ))}
      </View>
    </View>
  );
}

interface Props {
  aiEnginePersonalityAnalysis: AiEnginePersonalityAnalysis;
}

export function AiEnginePersonalityPage({ aiEnginePersonalityAnalysis }: Props) {
  const { engines, topEngineId } = aiEnginePersonalityAnalysis;
  const hasFirstParty = engines.some((e) => e.firstPartyOverlay !== null);

  return (
    <View>
      <Text style={s.heading}>AI Engine Profiles</Text>
      <Text style={s.subtext}>
        How the 5 major AI engines discover and cite content — engine-specific optimization approach
        {hasFirstParty ? " with 30-day performance data" : ""}
      </Text>

      {engines.map((card) => (
        <EngineCard
          key={card.engineId}
          card={card}
          isTop={card.engineId === topEngineId}
        />
      ))}
    </View>
  );
}
