import { View, Text, StyleSheet } from "@react-pdf/renderer";
import { C, S } from "../styles";
import type { EeatAudit } from "../../data-sources/eeat-audit";

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, color: C.muted, marginBottom: 12 },
  // Industry narrative
  narrativeBox: { backgroundColor: C.surface, borderRadius: 4, padding: 10, marginBottom: 14 },
  narrativeText: { fontSize: 9, color: C.body, lineHeight: 1.5 },
  // Composite score
  scoreBox: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 10, marginBottom: 14, flexDirection: "row", alignItems: "center", justifyContent: "space-between" },
  scoreLabelText: { fontSize: 9.5, fontFamily: "Helvetica-Bold", color: C.ink },
  scoreValue: { fontSize: 16, fontFamily: "Helvetica-Bold" },
  // Weight pill
  weightPill: { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2, alignSelf: "flex-start", marginBottom: 12 },
  weightPillText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.8 },
  // Dimension grid 2x2
  dimGrid: { flexDirection: "row", flexWrap: "wrap", marginHorizontal: -4, marginBottom: 14 },
  dimCard: { width: "48%", marginHorizontal: "1%", marginBottom: 8, borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8 },
  dimHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 5 },
  dimLabel: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink },
  dimScore: { fontSize: 10, fontFamily: "Helvetica-Bold" },
  // Score bar
  barBg: { height: 4, backgroundColor: "#e2e8f0", borderRadius: 2, marginBottom: 6 },
  barFill: { height: 4, borderRadius: 2 },
  // Signal lines
  sigLine: { flexDirection: "row", alignItems: "flex-start", gap: 4, marginBottom: 2 },
  sigCheck: { fontSize: 7.5, color: "#059669", width: 8 },
  sigX: { fontSize: 7.5, color: "#dc2626", width: 8 },
  sigText: { fontSize: 7.5, color: C.body, lineHeight: 1.3, flex: 1 },
  sigMutedText: { fontSize: 7.5, color: C.muted, lineHeight: 1.3, flex: 1 },
  sigDivider: { borderTopWidth: 0.5, borderTopColor: C.border, marginVertical: 4 },
  // Top gaps section
  sectionLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 8 },
  gapCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8, marginBottom: 6 },
  gapHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 4 },
  gapDimBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  gapDimText: { fontSize: 6.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  gapRight: { flexDirection: "row", gap: 6, alignItems: "center" },
  diffBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  diffText: { fontSize: 6.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  liftText: { fontSize: 8, fontFamily: "Helvetica-Bold", color: "#059669" },
  gapTitle: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 3, lineHeight: 1.3 },
  gapDesc: { fontSize: 8, color: C.body, lineHeight: 1.4 },
});

const WEIGHT_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 DIM_COLORS: Record<string, string> = {
  experience: "#3b82f6",
  expertise: "#7c3aed",
  authoritativeness: "#f59e0b",
  trustworthiness: "#10b981",
};

const DIM_LABELS: Record<string, string> = {
  experience: "Experience",
  expertise: "Expertise",
  authoritativeness: "Authoritativeness",
  trustworthiness: "Trustworthiness",
};

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

function scoreTextColor(score: number): string {
  if (score >= 70) return "#10b981";
  if (score >= 45) return "#f59e0b";
  return "#ef4444";
}

function barColor(score: number): string {
  if (score >= 70) return "#10b981";
  if (score >= 45) return "#f59e0b";
  return "#ef4444";
}

interface DimSignals {
  score: number;
  detectedSignals: string[];
  missingSignals: string[];
}

function DimCard({ dimKey, signals }: { dimKey: string; signals: DimSignals }) {
  const color = DIM_COLORS[dimKey] ?? "#64748b";
  const pct = Math.min(100, Math.max(0, signals.score));
  return (
    <View style={s.dimCard} wrap={false}>
      <View style={s.dimHeader}>
        <Text style={s.dimLabel}>{DIM_LABELS[dimKey] ?? dimKey}</Text>
        <Text style={[s.dimScore, { color: scoreTextColor(signals.score) }]}>{signals.score}/100</Text>
      </View>
      <View style={s.barBg}>
        <View style={[s.barFill, { width: `${pct}%`, backgroundColor: barColor(signals.score) }]} />
      </View>
      {signals.detectedSignals.slice(0, 2).map((sig, i) => (
        <View key={i} style={s.sigLine}>
          <Text style={s.sigCheck}>✓</Text>
          <Text style={s.sigText}>{sig}</Text>
        </View>
      ))}
      {signals.missingSignals.slice(0, 2).length > 0 && (
        <View style={s.sigDivider} />
      )}
      {signals.missingSignals.slice(0, 2).map((sig, i) => (
        <View key={i} style={s.sigLine}>
          <Text style={s.sigX}>✗</Text>
          <Text style={s.sigMutedText}>{sig}</Text>
        </View>
      ))}
    </View>
  );
}

interface Props {
  eeatAudit: EeatAudit;
}

export function EeatAuditPage({ eeatAudit }: Props) {
  const { compositeScore, industryWeight, experienceSignals, expertiseSignals, authoritativenessSignals, trustworthinessSignals, topGaps, industryContextNarrative } = eeatAudit;
  const weightColor = WEIGHT_COLORS[industryWeight] ?? WEIGHT_COLORS.moderate;

  return (
    <View>
      <Text style={s.heading}>E-E-A-T Audit</Text>
      <Text style={s.subheading}>Experience, Expertise, Authoritativeness, Trustworthiness</Text>

      {/* Industry weight pill */}
      <View style={[s.weightPill, { backgroundColor: weightColor.bg }]}>
        <Text style={[s.weightPillText, { color: weightColor.text }]}>
          {industryWeight.toUpperCase()} INDUSTRY WEIGHT
        </Text>
      </View>

      {/* Industry narrative */}
      <View style={s.narrativeBox}>
        <Text style={s.narrativeText}>{industryContextNarrative}</Text>
      </View>

      {/* Composite score */}
      <View style={s.scoreBox}>
        <Text style={s.scoreLabelText}>Composite E-E-A-T Score</Text>
        <Text style={[s.scoreValue, { color: scoreTextColor(compositeScore) }]}>{compositeScore}/100</Text>
      </View>

      {/* Dimension 2x2 grid */}
      <View style={s.dimGrid}>
        <DimCard dimKey="experience" signals={experienceSignals} />
        <DimCard dimKey="expertise" signals={expertiseSignals} />
        <DimCard dimKey="authoritativeness" signals={authoritativenessSignals} />
        <DimCard dimKey="trustworthiness" signals={trustworthinessSignals} />
      </View>

      {/* Top gaps table */}
      {topGaps.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>Top Gaps by Score Lift</Text>
          {topGaps.map((gap, i) => {
            const dimColor = { bg: "#f1f5f9", text: "#475569" };
            const diffColor = DIFF_COLORS[gap.implementationDifficulty] ?? DIFF_COLORS.moderate;
            return (
              <View key={i} style={s.gapCard} wrap={false}>
                <View style={s.gapHeader}>
                  <View style={[s.gapDimBadge, { backgroundColor: dimColor.bg }]}>
                    <Text style={[s.gapDimText, { color: dimColor.text }]}>
                      {DIM_LABELS[gap.dimension]?.toUpperCase() ?? gap.dimension}
                    </Text>
                  </View>
                  <View style={s.gapRight}>
                    <View style={[s.diffBadge, { backgroundColor: diffColor.bg }]}>
                      <Text style={[s.diffText, { color: diffColor.text }]}>
                        {gap.implementationDifficulty.toUpperCase()}
                      </Text>
                    </View>
                    <Text style={s.liftText}>+{gap.estimatedScoreLift} pts</Text>
                  </View>
                </View>
                <Text style={s.gapTitle}>{gap.gap}</Text>
                <Text style={s.gapDesc}>{gap.impactDescription}</Text>
              </View>
            );
          })}
        </View>
      )}
    </View>
  );
}
