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

const TIER_COLORS: Record<AuthorityTier, { score: string; bg: string; text: string }> = {
  Authoritative: { score: "#10b981", bg: "#d1fae5", text: "#065f46" },
  Established:   { score: "#3b82f6", bg: "#dbeafe", text: "#1e40af" },
  Emerging:      { score: "#f59e0b", bg: "#fef3c7", text: "#92400e" },
  Limited:       { score: "#ef4444", bg: "#fee2e2", text: "#991b1b" },
};

const STATUS_COLORS: Record<string, { bg: string; text: string }> = {
  strong:   { bg: "#d1fae5", text: "#065f46" },
  moderate: { bg: "#fef3c7", text: "#92400e" },
  weak:     { bg: "#ffedd5", text: "#9a3412" },
  absent:   { bg: "#fee2e2", text: "#991b1b" },
};

function signalBarColor(score: number): string {
  if (score >= 75) return "#10b981";
  if (score >= 45) return "#f59e0b";
  if (score >= 15) return "#f97316";
  return "#ef4444";
}

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, color: C.muted, marginBottom: 12 },
  // Hero strip
  heroBox: { flexDirection: "row", alignItems: "center", gap: 14, backgroundColor: C.surface, borderRadius: 4, padding: 10, marginBottom: 14, borderWidth: 0.75, borderColor: C.border },
  heroScore: { fontSize: 36, fontFamily: "Helvetica-Bold", width: 64, textAlign: "center" },
  heroRight: { flex: 1 },
  heroTierRow: { flexDirection: "row", alignItems: "center", gap: 6, marginBottom: 5 },
  tierPill: { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2 },
  tierPillText: { fontSize: 7, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  barBg: { height: 5, backgroundColor: "#e2e8f0", borderRadius: 2, marginBottom: 5 },
  barFill: { height: 5, borderRadius: 2 },
  heroNarrative: { fontSize: 8, color: C.body, lineHeight: 1.45 },
  // Signal grid -- 3 per row
  sectionLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 8 },
  signalGrid: { flexDirection: "row", flexWrap: "wrap", marginHorizontal: -3, marginBottom: 14 },
  signalCard: { width: "31.5%", marginHorizontal: "1%", marginBottom: 8, borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 7 },
  signalHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 4 },
  signalLabel: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.ink, flex: 1 },
  statusPill: { borderRadius: 2, paddingHorizontal: 4, paddingVertical: 1.5 },
  statusText: { fontSize: 6, fontFamily: "Helvetica-Bold", letterSpacing: 0.4 },
  signalBarBg: { height: 3, backgroundColor: "#e2e8f0", borderRadius: 1.5, marginBottom: 4 },
  signalBarFill: { height: 3, borderRadius: 1.5 },
  signalMeta: { flexDirection: "row", justifyContent: "space-between", marginBottom: 4 },
  signalMetaText: { fontSize: 6.5, color: C.muted },
  evidenceLine: { fontSize: 7, color: C.body, lineHeight: 1.35, marginBottom: 2 },
  recBox: { backgroundColor: "#f8fafc", borderRadius: 2, padding: 4, marginTop: 3 },
  recText: { fontSize: 6.5, color: C.body, lineHeight: 1.35 },
  // Recommendations
  recPanel: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 10, marginBottom: 12 },
  recItem: { flexDirection: "row", gap: 6, marginBottom: 7 },
  recBadge: { width: 14, height: 14, borderRadius: 7, backgroundColor: C.surface, alignItems: "center", justifyContent: "center" },
  recBadgeText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted },
  recItemText: { fontSize: 8, color: C.body, lineHeight: 1.4, flex: 1 },
  // Patent footer
  footerBox: { borderTopWidth: 0.5, borderTopColor: C.border, paddingTop: 8 },
  footerText: { fontSize: 7, color: C.muted, lineHeight: 1.4 },
});

function SignalCard({ signal }: { signal: AuthoritySignal }) {
  const statusCfg = STATUS_COLORS[signal.status] ?? STATUS_COLORS["absent"]!;
  const barColor = signalBarColor(signal.rawScore);
  const pct = Math.min(100, signal.rawScore);
  const firstEvidence = signal.evidence[0] ?? "";
  return (
    <View style={s.signalCard}>
      <View style={s.signalHeader}>
        <Text style={s.signalLabel}>{signal.label}</Text>
        <View style={[s.statusPill, { backgroundColor: statusCfg.bg }]}>
          <Text style={[s.statusText, { color: statusCfg.text }]}>{signal.status.charAt(0).toUpperCase() + signal.status.slice(1)}</Text>
        </View>
      </View>
      <View style={s.signalBarBg}>
        <View style={[s.signalBarFill, { width: `${pct}%`, backgroundColor: barColor }]} />
      </View>
      <View style={s.signalMeta}>
        <Text style={s.signalMetaText}>Score: {signal.rawScore}/100</Text>
        <Text style={s.signalMetaText}>Wt: {Math.round(signal.weight * 100)}%</Text>
      </View>
      {firstEvidence.length > 0 && (
        <Text style={s.evidenceLine}>{firstEvidence.slice(0, 120)}</Text>
      )}
      {signal.recommendation && (
        <View style={s.recBox}>
          <Text style={s.recText}>{signal.recommendation.slice(0, 140)}</Text>
        </View>
      )}
    </View>
  );
}

interface Props {
  brandAuthorityScore: BrandAuthorityScore;
}

export function BrandAuthorityScorePage({ brandAuthorityScore }: Props) {
  const { overall, tier, signals, topRecommendations, narrativeSummary, patentRelevance } = brandAuthorityScore;
  const tierCfg = TIER_COLORS[tier];
  const pct = Math.min(100, overall);

  return (
    <View>
      <Text style={s.heading}>Brand Authority Score</Text>
      <Text style={s.subheading}>
        Composite signal measuring AI-engine citation-worthiness across six authority dimensions
      </Text>

      {/* Hero strip */}
      <View style={s.heroBox}>
        <Text style={[s.heroScore, { color: tierCfg.score }]}>{overall}</Text>
        <View style={s.heroRight}>
          <View style={s.heroTierRow}>
            <View style={[s.tierPill, { backgroundColor: tierCfg.bg }]}>
              <Text style={[s.tierPillText, { color: tierCfg.text }]}>{tier.toUpperCase()}</Text>
            </View>
          </View>
          <View style={s.barBg}>
            <View style={[s.barFill, { width: `${pct}%`, backgroundColor: tierCfg.score }]} />
          </View>
          <Text style={s.heroNarrative}>{narrativeSummary}</Text>
        </View>
      </View>

      {/* 6-signal grid */}
      <Text style={s.sectionLabel}>Authority Signals</Text>
      <View style={s.signalGrid}>
        {signals.map((signal, i) => (
          <SignalCard key={i} signal={signal} />
        ))}
      </View>

      {/* Top 3 recommendations */}
      {topRecommendations.length > 0 && (
        <>
          <Text style={s.sectionLabel}>Top Recommendations</Text>
          <View style={s.recPanel}>
            {topRecommendations.map((rec, i) => (
              <View key={i} style={s.recItem}>
                <View style={s.recBadge}>
                  <Text style={s.recBadgeText}>{i + 1}</Text>
                </View>
                <Text style={s.recItemText}>{rec}</Text>
              </View>
            ))}
          </View>
        </>
      )}

      {/* Methodology footer */}
      <View style={s.footerBox}>
        <Text style={s.footerText}>{patentRelevance}</Text>
      </View>
    </View>
  );
}
