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

const SEVERITY_COLOR: Record<string, string> = {
  critical: C.red,
  high: "#ea580c",
  medium: C.amber,
  low: C.muted,
};

const PAGE_TYPE_COLOR: Record<string, string> = {
  homepage: "#6366f1",
  contact: C.green,
  service: "#2563eb",
  product: "#0891b2",
  about: "#7c3aed",
  blog: C.muted,
  pricing: C.amber,
  faq: "#0d9488",
  other: C.muted,
};

function scoreColor(score: number): string {
  if (score >= 70) return C.green;
  if (score >= 45) return C.amber;
  return C.red;
}

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subtext: { ...S.small, marginBottom: 12 },
  statStrip: { flexDirection: "row", gap: 8, marginBottom: 14 },
  statBox: {
    flex: 1,
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 10,
    backgroundColor: C.surface,
  },
  statLabel: { ...S.label, marginBottom: 3 },
  statValue: { fontSize: 20, fontFamily: "Helvetica-Bold", color: C.ink, lineHeight: 1 },
  card: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    marginBottom: 8,
    overflow: "hidden",
    backgroundColor: C.white,
  },
  cardHeader: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
    paddingHorizontal: 10,
    paddingVertical: 7,
    backgroundColor: C.surface,
    borderBottomWidth: 0.5,
    borderBottomColor: C.border,
  },
  scoreCircle: {
    width: 32,
    height: 32,
    borderRadius: 16,
    borderWidth: 1.5,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: C.white,
  },
  scoreText: { fontSize: 9, fontFamily: "Helvetica-Bold" },
  typePill: {
    paddingHorizontal: 5,
    paddingVertical: 2,
    borderRadius: 3,
    fontSize: 7,
    fontFamily: "Helvetica-Bold",
    letterSpacing: 0.5,
    color: C.white,
  },
  urlText: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.body, flex: 1 },
  selectionReason: { fontSize: 7.5, color: C.muted, flex: 1.5 },
  signalsRow: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 6,
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderBottomWidth: 0.5,
    borderBottomColor: C.border,
  },
  signal: { flexDirection: "row", alignItems: "center", gap: 3 },
  signalDot: { width: 5, height: 5, borderRadius: 2.5 },
  signalText: { fontSize: 7.5, color: C.muted },
  issuesBlock: {
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderBottomWidth: 0.5,
    borderBottomColor: C.border,
  },
  issueLine: { flexDirection: "row", alignItems: "flex-start", gap: 5, marginBottom: 3 },
  severityBadge: {
    paddingHorizontal: 4,
    paddingVertical: 1.5,
    borderRadius: 2,
    fontSize: 6.5,
    fontFamily: "Helvetica-Bold",
    letterSpacing: 0.4,
    color: C.white,
    marginTop: 1,
  },
  issueText: { fontSize: 8, color: C.body, flex: 1, lineHeight: 1.4 },
  recBlock: { paddingHorizontal: 10, paddingVertical: 7 },
  recLabel: { ...S.label, marginBottom: 3 },
  recText: { fontSize: 8, color: C.muted, lineHeight: 1.4 },
});

function PageCard({ card }: { card: PageHealthCard }) {
  const path = card.url.replace(/^https?:\/\/[^/]+/, "") || "/";
  const sc = scoreColor(card.healthScore);
  const tc = PAGE_TYPE_COLOR[card.pageType] ?? C.muted;

  const signals: Array<{ label: string; ok: boolean; value?: string }> = [
    { label: "H1", ok: card.structuralSignals.hasH1 },
    { label: "Schema", ok: card.structuralSignals.hasSchema, value: card.structuralSignals.schemaTypes.slice(0, 2).join(", ") || undefined },
    { label: "CTA", ok: card.structuralSignals.hasCTA ?? false },
    { label: card.structuralSignals.wordCount != null ? `${card.structuralSignals.wordCount}w` : "Content", ok: (card.structuralSignals.wordCount ?? 0) >= 300 },
  ];
  if (card.behavioralSignals?.bounceRate != null) {
    signals.push({ label: `Bounce ${Math.round(card.behavioralSignals.bounceRate * 100)}%`, ok: card.behavioralSignals.bounceRate < 0.55 });
  }
  if (card.aiSignals) {
    signals.push({ label: `AI: ${card.aiSignals.aiVisits30d} visits`, ok: card.aiSignals.aiVisits30d > 0 });
  }

  return (
    <View style={s.card} wrap={false}>
      <View style={s.cardHeader}>
        <View style={[s.scoreCircle, { borderColor: sc }]}>
          <Text style={[s.scoreText, { color: sc }]}>{card.healthScore}</Text>
        </View>
        <Text style={[s.typePill, { backgroundColor: tc }]}>{card.pageType.toUpperCase()}</Text>
        <Text style={s.urlText}>{path}</Text>
        <Text style={s.selectionReason}>{card.selectionReason}</Text>
      </View>

      <View style={s.signalsRow}>
        {signals.map((sig, i) => (
          <View key={i} style={s.signal}>
            <View style={[s.signalDot, { backgroundColor: sig.ok ? C.green : C.red }]} />
            <Text style={s.signalText}>{sig.value ?? sig.label}</Text>
          </View>
        ))}
      </View>

      {card.topIssues.length > 0 && (
        <View style={s.issuesBlock}>
          {card.topIssues.map((issue, i) => (
            <View key={i} style={s.issueLine}>
              <Text style={[s.severityBadge, { backgroundColor: SEVERITY_COLOR[issue.severity] ?? C.muted }]}>
                {issue.severity.toUpperCase()}
              </Text>
              <Text style={s.issueText}>{issue.issue}</Text>
            </View>
          ))}
        </View>
      )}

      <View style={s.recBlock}>
        <Text style={s.recLabel}>TOP RECOMMENDATION</Text>
        <Text style={s.recText}>{card.topRecommendation}</Text>
      </View>
    </View>
  );
}

interface Props {
  pageStrategicPass: PageStrategicPass;
}

export function PageStrategicPassPage({ pageStrategicPass }: Props) {
  const { pages } = pageStrategicPass;
  const avgScore = Math.round(pages.reduce((s, p) => s + p.healthScore, 0) / pages.length);
  const criticalCount = pages.reduce((n, p) => n + p.topIssues.filter((i) => i.severity === "critical").length, 0);

  return (
    <View>
      <Text style={s.heading}>Page-by-Page Review</Text>
      <Text style={s.subtext}>
        Structural health assessment for {pages.length} high-priority page{pages.length !== 1 ? "s" : ""}
      </Text>

      <View style={s.statStrip}>
        <View style={s.statBox}>
          <Text style={s.statLabel}>PAGES REVIEWED</Text>
          <Text style={s.statValue}>{pages.length}</Text>
        </View>
        <View style={s.statBox}>
          <Text style={s.statLabel}>AVG HEALTH SCORE</Text>
          <Text style={[s.statValue, { color: scoreColor(avgScore) }]}>{avgScore}/100</Text>
        </View>
        <View style={s.statBox}>
          <Text style={s.statLabel}>CRITICAL ISSUES</Text>
          <Text style={[s.statValue, { color: criticalCount > 0 ? C.red : C.green }]}>{criticalCount}</Text>
        </View>
      </View>

      {pages.map((card) => (
        <PageCard key={card.url} card={card} />
      ))}
    </View>
  );
}
