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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 6 },
  subtext: { ...S.small, marginBottom: 18 },
  statStrip: { flexDirection: "row", gap: 10, marginBottom: 18 },
  statBox: {
    flex: 1,
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 12,
    backgroundColor: C.surface,
  },
  statLabel: { ...S.label, marginBottom: 5 },
  statValue: { fontSize: 26, fontFamily: "Helvetica-Bold", color: C.ink, lineHeight: 1 },
  statSub: { fontSize: 8, color: C.muted, marginTop: 4 },
  statDelta: { fontSize: 9, fontFamily: "Helvetica-Bold", marginTop: 4 },
  // Anchor distribution
  anchorSection: { marginBottom: 18 },
  anchorLabel: { ...S.label, marginBottom: 8 },
  anchorTrack: { height: 14, flexDirection: "row", borderRadius: 4, overflow: "hidden" },
  anchorLegend: { flexDirection: "row", flexWrap: "wrap", gap: 10, marginTop: 8 },
  legendItem: { flexDirection: "row", alignItems: "center", gap: 4 },
  legendDot: { width: 8, height: 8, borderRadius: 4 },
  legendText: { fontSize: 8, color: C.body },
  // Referrers table
  tableBlock: { marginBottom: 14 },
  tableLabel: { ...S.label, marginBottom: 7 },
  table: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    overflow: "hidden",
  },
  headerRow: {
    flexDirection: "row",
    backgroundColor: C.surface,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderBottomWidth: 0.75,
    borderBottomColor: C.border,
  },
  row: {
    flexDirection: "row",
    paddingHorizontal: 12,
    paddingVertical: 9,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  rowAlt: { backgroundColor: "#fafafa" },
  colDomain: { flex: 3, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  colRank: { flex: 1.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "center" },
  colDate: { flex: 2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  domainText: { flex: 3, fontSize: 9.5, color: C.accent },
  rankText: { flex: 1.5, fontSize: 9.5, color: C.body, fontFamily: "Helvetica-Bold", textAlign: "center" },
  dateText: { flex: 2, fontSize: 9, color: C.muted },
  // Toxicity warning
  toxicityBox: {
    borderWidth: 1,
    borderColor: C.red,
    borderRadius: 4,
    padding: 14,
    backgroundColor: "#fef2f2",
  },
  toxicityHeader: { fontSize: 11, fontFamily: "Helvetica-Bold", color: "#991b1b", marginBottom: 6 },
  toxicityBody: { fontSize: 9.5, color: "#991b1b", lineHeight: 1.55, marginBottom: 10 },
  toxicTable: { borderWidth: 0.5, borderColor: "#fecaca", borderRadius: 3, overflow: "hidden" },
  toxicRow: {
    flexDirection: "row",
    paddingHorizontal: 10,
    paddingVertical: 7,
    borderBottomWidth: 0.5,
    borderBottomColor: "#fecaca",
    alignItems: "center",
  },
  toxicDomain: { flex: 3, fontSize: 9, color: "#991b1b" },
  toxicScore: { flex: 1, fontSize: 9, color: C.red, fontFamily: "Helvetica-Bold", textAlign: "right" },
});

const ANCHOR_COLORS = {
  branded: C.accent,
  exact: "#7c3aed",
  partial: C.amber,
  generic: "#94a3b8",
  url: "#64748b",
};

function fmt(n: number | null | undefined): string {
  if (n == null) return "—";
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return String(n);
}

function drRating(dr: number | null | undefined): { label: string; color: string } {
  if (dr == null) return { label: "—", color: C.muted };
  if (dr >= 60) return { label: "Strong", color: C.green };
  if (dr >= 30) return { label: "Moderate", color: C.amber };
  return { label: "Low", color: C.red };
}

interface Props {
  seo: SeoSection;
}

export function AuthorityProfilePage({ seo }: Props) {
  const bl = seo.backlinkProfile;
  if (!bl || (bl.referringDomains === 0 && bl.totalBacklinks === 0)) return null;

  const dr = drRating(bl.domainRank);
  const anchor = bl.anchorDistribution;
  const referrers = bl.topReferrers ?? [];
  const topReferrers = referrers.slice(0, 5);

  // Build anchor bar segments (only if data present)
  const anchorTypes: Array<{ key: keyof typeof ANCHOR_COLORS; label: string }> = [
    { key: "branded", label: "Branded" },
    { key: "exact", label: "Exact" },
    { key: "partial", label: "Partial" },
    { key: "generic", label: "Generic" },
    { key: "url", label: "URL" },
  ];

  const hasAnchor = anchor && Object.values(anchor).some((v) => v != null && v > 0);

  return (
    <View>
      <Text style={s.heading}>Authority Profile</Text>
      <Text style={s.subtext}>Domain authority signals and inbound link volume from the web.</Text>

      {/* Stat strip */}
      <View style={s.statStrip}>
        <View style={s.statBox}>
          <Text style={s.statLabel}>Domain Authority</Text>
          <Text style={[s.statValue, { color: bl.domainRank != null ? dr.color : C.muted }]}>
            {bl.domainRank ?? "—"}
          </Text>
          <Text style={s.statSub}>{dr.label}</Text>
        </View>
        <View style={s.statBox}>
          <Text style={s.statLabel}>Referring Domains</Text>
          <Text style={s.statValue}>{fmt(bl.referringDomains)}</Text>
          {bl.gained30d != null && (
            <Text style={[s.statDelta, { color: (bl.gained30d ?? 0) > 0 ? C.green : C.muted }]}>
              {(bl.gained30d ?? 0) > 0 ? `↑ ${bl.gained30d} gained` : "—"} {bl.lost30d != null && bl.lost30d > 0 ? `/ ↓ ${bl.lost30d} lost` : ""} (30d)
            </Text>
          )}
        </View>
        <View style={s.statBox}>
          <Text style={s.statLabel}>Total Backlinks</Text>
          <Text style={s.statValue}>{fmt(bl.totalBacklinks)}</Text>
          <Text style={s.statSub}>total inbound links</Text>
        </View>
        <View style={s.statBox}>
          <Text style={s.statLabel}>Spam Risk</Text>
          <Text style={[s.statValue, { fontSize: 18, marginTop: 4 }, {
            color: (bl.spamScore ?? 0) < 10 ? C.green : (bl.spamScore ?? 0) < 30 ? C.amber : C.red,
          }]}>
            {bl.spamScore != null ? `${bl.spamScore}%` : "—"}
          </Text>
          <Text style={s.statSub}>{(bl.spamScore ?? 0) < 10 ? "Low risk" : (bl.spamScore ?? 0) < 30 ? "Moderate risk" : "High risk"}</Text>
        </View>
      </View>

      {/* Anchor distribution bar */}
      {hasAnchor && anchor && (
        <View style={s.anchorSection}>
          <Text style={s.anchorLabel}>Anchor Text Distribution</Text>
          <View style={s.anchorTrack}>
            {anchorTypes.map(({ key, label }) => {
              const pct = anchor[key] ?? 0;
              if (pct === 0) return null;
              return (
                <View key={key} style={{ width: `${pct}%`, backgroundColor: ANCHOR_COLORS[key] }}>
                  {pct >= 8 && (
                    <Text style={{ fontSize: 7, color: "#fff", textAlign: "center", paddingTop: 2 }}>
                      {Math.round(pct)}%
                    </Text>
                  )}
                </View>
              );
            })}
          </View>
          <View style={s.anchorLegend}>
            {anchorTypes.map(({ key, label }) => {
              const pct = anchor[key];
              if (!pct) return null;
              return (
                <View key={key} style={s.legendItem}>
                  <View style={[s.legendDot, { backgroundColor: ANCHOR_COLORS[key] }]} />
                  <Text style={s.legendText}>{label} {Math.round(pct)}%</Text>
                </View>
              );
            })}
          </View>
        </View>
      )}

      {/* Top referrers table */}
      {topReferrers.length > 0 && (
        <View style={s.tableBlock}>
          <Text style={s.tableLabel}>Top Referring Domains</Text>
          <View style={s.table}>
            <View style={s.headerRow}>
              <Text style={s.colDomain}>DOMAIN</Text>
              <Text style={s.colRank}>DR</Text>
              <Text style={s.colDate}>FIRST SEEN</Text>
            </View>
            {topReferrers.map((r, i) => (
              <View
                key={i}
                style={[s.row, i % 2 === 1 ? s.rowAlt : {}, i === topReferrers.length - 1 ? { borderBottomWidth: 0 } : {}]}
              >
                <Text style={s.domainText}>{r.domain}</Text>
                <Text style={s.rankText}>{r.domainRank ?? "—"}</Text>
                <Text style={s.dateText}>{r.firstSeen ?? "—"}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Toxicity warning */}
      {bl.toxicityFlag && (
        <View style={s.toxicityBox}>
          <Text style={s.toxicityHeader}>Authority Risk Detected</Text>
          <Text style={s.toxicityBody}>
            {`Spam score of ${bl.spamScore ?? "?"}% detected across referring domain set. Consider disavow file review for the highest-spam-score referrers below.`}
          </Text>
          {referrers.filter((r) => (r.spamScore ?? 0) > 0).slice(0, 3).length > 0 && (
            <View style={s.toxicTable}>
              {referrers
                .filter((r) => (r.spamScore ?? 0) > 0)
                .sort((a, b) => (b.spamScore ?? 0) - (a.spamScore ?? 0))
                .slice(0, 3)
                .map((r, i) => (
                  <View key={i} style={[s.toxicRow, i === 2 ? { borderBottomWidth: 0 } : {}]}>
                    <Text style={s.toxicDomain}>{r.domain}</Text>
                    <Text style={s.toxicScore}>Spam {r.spamScore}%</Text>
                  </View>
                ))}
            </View>
          )}
        </View>
      )}
    </View>
  );
}
