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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subtext: { ...S.small, marginBottom: 16 },
  pill: { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2, alignSelf: "flex-start", marginBottom: 16 },
  pillText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.8 },
  // Competitor block
  compBlock: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 12,
    marginBottom: 12,
    backgroundColor: C.surface,
  },
  compDomain: { fontSize: 11, fontFamily: "Helvetica-Bold", color: C.accent, marginBottom: 2 },
  compLabel: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, marginBottom: 6 },
  statsRow: { flexDirection: "row", gap: 16, marginBottom: 8 },
  statBox: { alignItems: "center" },
  statNum: { fontSize: 11, fontFamily: "Helvetica-Bold", color: C.ink },
  statLabel: { fontSize: 7, color: C.muted, marginTop: 1 },
  schemaPill: {
    borderRadius: 2,
    paddingHorizontal: 6,
    paddingVertical: 2,
    backgroundColor: "#eef2ff",
    marginRight: 4,
    marginBottom: 4,
  },
  schemaPillText: { fontSize: 7.5, color: C.accent },
  schemaRow: { flexDirection: "row", flexWrap: "wrap", marginBottom: 6 },
  subHeading: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, marginBottom: 3 },
  bodyText: { fontSize: 9, color: C.body, lineHeight: 1.5 },
  muted: { fontSize: 8, color: C.muted, lineHeight: 1.4 },
  diffBox: {
    borderRadius: 3,
    backgroundColor: "#f1f5f9",
    padding: 8,
    marginTop: 6,
  },
  // Gap matrix
  table: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, overflow: "hidden", marginTop: 12 },
  headerRow: {
    flexDirection: "row",
    backgroundColor: C.surface,
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderBottomWidth: 0.75,
    borderBottomColor: C.border,
  },
  tableRow: {
    flexDirection: "row",
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  rowAlt: { backgroundColor: "#fafafa" },
  colHeader: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  cellText: { fontSize: 9, color: C.body },
  cellBrand: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink },
  rankBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1 },
  rankText: { fontSize: 7.5, fontFamily: "Helvetica-Bold" },
  sectionDivider: { marginTop: 18, marginBottom: 6, borderTopWidth: 0.75, borderTopColor: C.border },
  sectionHeading: { fontSize: 11, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 8 },
});

function fmt(n: number | null | undefined): string {
  if (n == null) return "—";
  return n.toLocaleString();
}

function rankColor(rank: 1 | 2 | 3 | 4): string {
  return rank === 1 ? C.green : rank <= 2 ? C.amber : C.red;
}

function CompetitorBlock({ comp, label }: { comp: CompetitorAnalysis["detectedCompetitors"][0]; label: string }) {
  const presentSchema = comp.detectedSchema.filter((s) => s.present);
  return (
    <View style={s.compBlock} wrap={false}>
      <Text style={s.compLabel}>{label.toUpperCase()}</Text>
      <Text style={s.compDomain}>{comp.domain}</Text>
      <View style={s.statsRow}>
        <View style={s.statBox}>
          <Text style={s.statNum}>{fmt(comp.domainAuthority)}</Text>
          <Text style={s.statLabel}>Domain Auth</Text>
        </View>
        <View style={s.statBox}>
          <Text style={s.statNum}>{fmt(comp.referringDomains)}</Text>
          <Text style={s.statLabel}>Ref Domains</Text>
        </View>
        <View style={s.statBox}>
          <Text style={s.statNum}>{fmt(comp.totalBacklinks)}</Text>
          <Text style={s.statLabel}>Backlinks</Text>
        </View>
        <View style={s.statBox}>
          <Text style={s.statNum}>#{comp.avgRankPosition}</Text>
          <Text style={s.statLabel}>Avg Rank</Text>
        </View>
      </View>

      {presentSchema.length > 0 && (
        <View style={{ marginBottom: 6 }}>
          <Text style={s.subHeading}>Schema Detected</Text>
          <View style={s.schemaRow}>
            {presentSchema.map((sc) => (
              <View key={sc.type} style={s.schemaPill}>
                <Text style={s.schemaPillText}>{sc.type}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {comp.topContentTopics.length > 0 && (
        <View style={{ marginBottom: 6 }}>
          <Text style={s.subHeading}>Top Content Topics</Text>
          <Text style={s.muted}>{comp.topContentTopics.slice(0, 5).join(" · ")}</Text>
        </View>
      )}

      {comp.keyDifferentiator && (
        <View style={s.diffBox}>
          <Text style={s.subHeading}>What They Do Differently</Text>
          <Text style={s.bodyText}>{comp.keyDifferentiator}</Text>
        </View>
      )}
    </View>
  );
}

function GapMatrixTable({ ca }: { ca: CompetitorAnalysis }) {
  const dims = ca.competitiveGapMatrix.dimensions;
  const comps = ca.detectedCompetitors;
  return (
    <View wrap={false}>
      <Text style={s.sectionHeading}>Competitive Gap Matrix</Text>
      <View style={s.table}>
        <View style={s.headerRow}>
          <Text style={[s.colHeader, { flex: 4 }]}>Dimension</Text>
          <Text style={[s.colHeader, { flex: 2, textAlign: "right" }]}>Your Site</Text>
          {comps[0] && <Text style={[s.colHeader, { flex: 2.5, textAlign: "right" }]}>{comps[0].domain.split(".")[0]}</Text>}
          {comps[1] && <Text style={[s.colHeader, { flex: 2.5, textAlign: "right" }]}>{comps[1].domain.split(".")[0]}</Text>}
          {comps[2] && <Text style={[s.colHeader, { flex: 2.5, textAlign: "right" }]}>{comps[2].domain.split(".")[0]}</Text>}
          <Text style={[s.colHeader, { flex: 1.5, textAlign: "center" }]}>Rank</Text>
        </View>
        {dims.map((dim, i) => (
          <View key={dim.name} style={[s.tableRow, i % 2 === 1 ? s.rowAlt : {}]}>
            <Text style={[s.cellText, { flex: 4 }]}>{dim.name}</Text>
            <Text style={[s.cellBrand, { flex: 2, textAlign: "right" }]}>{String(dim.brandValue)}</Text>
            {comps[0] && <Text style={[s.cellText, { flex: 2.5, textAlign: "right" }]}>{String(dim.competitorAValue)}</Text>}
            {comps[1] && <Text style={[s.cellText, { flex: 2.5, textAlign: "right" }]}>{String(dim.competitorBValue)}</Text>}
            {comps[2] && <Text style={[s.cellText, { flex: 2.5, textAlign: "right" }]}>{String(dim.competitorCValue)}</Text>}
            <View style={[s.rankBadge, { flex: 1.5, alignItems: "center", backgroundColor: rankColor(dim.brandRank) + "22" }]}>
              <Text style={[s.rankText, { color: rankColor(dim.brandRank) }]}>#{dim.brandRank}</Text>
            </View>
          </View>
        ))}
      </View>
    </View>
  );
}

interface Props {
  competitorAnalysis: CompetitorAnalysis;
}

export function CompetitorDeepDivePage({ competitorAnalysis: ca }: Props) {
  const conf = ca.dataQuality;
  const confColor = conf === "high" ? C.green : conf === "moderate" ? C.amber : C.muted;
  const confLabel = conf === "high" ? "High confidence" : conf === "moderate" ? "Moderate confidence" : "Limited data";

  return (
    <View>
      <Text style={s.heading}>Competitive Intelligence</Text>
      <Text style={s.subtext}>
        Top-ranking competitors identified across your tracked industry queries.
      </Text>
      <View style={[s.pill, { backgroundColor: conf === "high" ? C.greenLight : conf === "moderate" ? C.amberLight : "#f3f4f6" }]}>
        <Text style={[s.pillText, { color: confColor }]}>{confLabel.toUpperCase()}</Text>
      </View>

      {ca.detectedCompetitors.map((comp, i) => (
        <CompetitorBlock
          key={comp.domain}
          comp={comp}
          label={i === 0 ? "Competitor A" : i === 1 ? "Competitor B" : "Competitor C"}
        />
      ))}

      <View style={s.sectionDivider} />
      <GapMatrixTable ca={ca} />
    </View>
  );
}
