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: 4 },
  subheading: { fontSize: 10, color: C.muted, marginBottom: 6 },
  narrative: { ...S.body, lineHeight: 1.6, marginBottom: 16 },
  kpiRow: { flexDirection: "row", gap: 10, marginBottom: 18 },
  kpiBox: {
    flex: 1,
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 12,
    backgroundColor: C.surface,
  },
  kpiLabel: { ...S.label, marginBottom: 5 },
  kpiValue: { fontSize: 24, fontFamily: "Helvetica-Bold", color: C.ink, lineHeight: 1 },
  kpiSub: { fontSize: 8, color: C.muted, marginTop: 4 },
  // Query table
  tableBlock: { marginBottom: 18 },
  tableLabel: { ...S.label, marginBottom: 7 },
  table: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    overflow: "hidden",
  },
  headerRow: {
    flexDirection: "row",
    backgroundColor: C.surface,
    paddingHorizontal: 10,
    paddingVertical: 7,
    borderBottomWidth: 0.75,
    borderBottomColor: C.border,
  },
  row: {
    flexDirection: "row",
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  rowAlt: { backgroundColor: "#fafafa" },
  rowUnderperformer: { backgroundColor: "#fffbeb" },
  colQuery: { flex: 4, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  colNum: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  queryText: { flex: 4, fontSize: 8.5, color: C.body, lineHeight: 1.3 },
  clicksText: { flex: 1.2, fontSize: 9, color: C.ink, fontFamily: "Helvetica-Bold", textAlign: "right" },
  imprText: { flex: 1.2, fontSize: 9, color: C.muted, textAlign: "right" },
  ctrText: { flex: 1.2, fontSize: 9, color: C.body, textAlign: "right" },
  posText: { flex: 1.2, fontSize: 9, color: C.body, textAlign: "right" },
  // Histogram
  histSection: { marginBottom: 14 },
  histLabel: { ...S.label, marginBottom: 8 },
  histRow: { flexDirection: "row", alignItems: "flex-end", gap: 4, height: 60 },
  histBarWrapper: { flex: 1, alignItems: "center" },
  histBar: { width: "80%", borderRadius: 2 },
  histBarLabel: { fontSize: 7.5, color: C.muted, marginTop: 3, textAlign: "center" },
  histCount: { fontSize: 8, fontFamily: "Helvetica-Bold", marginBottom: 2, textAlign: "center" },
});

const HIST_COLORS = ["#16a34a", "#3b82f6", C.amber, "#94a3b8", "#d1d5db"];

function fmtNum(n: number): string {
  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 posColor(p: number): string {
  if (p <= 3) return C.green;
  if (p <= 10) return "#2563eb";
  if (p <= 20) return C.amber;
  return C.muted;
}

interface Props {
  seo: SeoSection;
}

export function OrganicSearchPerformancePage({ seo }: Props) {
  const gsc = seo.organicSearchSummary;
  if (!gsc) return null;

  // Position distribution from topQueries
  const buckets = [0, 0, 0, 0, 0]; // 1-3, 4-10, 11-20, 21-50, 51+
  gsc.topQueries.forEach((q) => {
    if (q.position <= 3) buckets[0]++;
    else if (q.position <= 10) buckets[1]++;
    else if (q.position <= 20) buckets[2]++;
    else if (q.position <= 50) buckets[3]++;
    else buckets[4]++;
  });
  const maxBucket = Math.max(...buckets, 1);

  const topQueries = gsc.topQueries.slice(0, 15);

  return (
    <View>
      <Text style={s.heading}>Organic Search Performance</Text>
      <Text style={s.subheading}>Trailing 30 days</Text>

      {gsc.narrative ? (
        <Text style={s.narrative}>{gsc.narrative}</Text>
      ) : null}

      {/* KPI strip */}
      <View style={s.kpiRow}>
        <View style={s.kpiBox}>
          <Text style={s.kpiLabel}>Total Clicks</Text>
          <Text style={s.kpiValue}>{fmtNum(gsc.totalClicks30d)}</Text>
          <Text style={s.kpiSub}>30-day organic clicks</Text>
        </View>
        <View style={s.kpiBox}>
          <Text style={s.kpiLabel}>Impressions</Text>
          <Text style={s.kpiValue}>{fmtNum(gsc.totalImpressions30d)}</Text>
          <Text style={s.kpiSub}>30-day search views</Text>
        </View>
        <View style={s.kpiBox}>
          <Text style={s.kpiLabel}>Avg. CTR</Text>
          <Text style={[s.kpiValue, { color: gsc.avgCtr >= 5 ? C.green : gsc.avgCtr >= 2 ? C.amber : C.red }]}>
            {gsc.avgCtr.toFixed(1)}%
          </Text>
          <Text style={s.kpiSub}>click-through rate</Text>
        </View>
        <View style={s.kpiBox}>
          <Text style={s.kpiLabel}>Avg. Position</Text>
          <Text style={[s.kpiValue, { color: posColor(gsc.avgPosition) }]}>
            {gsc.avgPosition.toFixed(1)}
          </Text>
          <Text style={s.kpiSub}>avg. SERP rank</Text>
        </View>
      </View>

      {/* Position distribution histogram */}
      {gsc.topQueries.length > 0 && (
        <View style={s.histSection}>
          <Text style={s.histLabel}>Position Distribution</Text>
          <View style={s.histRow}>
            {buckets.map((count, i) => {
              const labels = ["1–3", "4–10", "11–20", "21–50", "51+"];
              const heightPct = (count / maxBucket) * 56;
              return (
                <View key={i} style={s.histBarWrapper}>
                  <Text style={[s.histCount, { color: HIST_COLORS[i] }]}>{count > 0 ? count : ""}</Text>
                  <View style={[s.histBar, { height: Math.max(heightPct, count > 0 ? 4 : 0), backgroundColor: HIST_COLORS[i] }]} />
                  <Text style={s.histBarLabel}>{labels[i]}</Text>
                </View>
              );
            })}
          </View>
        </View>
      )}

      {/* Top queries table */}
      {topQueries.length > 0 && (
        <View style={s.tableBlock}>
          <Text style={s.tableLabel}>Top Queries</Text>
          <View style={s.table}>
            <View style={s.headerRow}>
              <Text style={s.colQuery}>QUERY</Text>
              <Text style={s.colNum}>CLICKS</Text>
              <Text style={s.colNum}>IMPR.</Text>
              <Text style={s.colNum}>CTR</Text>
              <Text style={s.colNum}>POS.</Text>
            </View>
            {topQueries.map((q, i) => {
              const isUnderperformer = q.impressions > 100 && q.clicks / q.impressions < 0.01;
              return (
                <View
                  key={i}
                  style={[
                    s.row,
                    isUnderperformer ? s.rowUnderperformer : i % 2 === 1 ? s.rowAlt : {},
                    i === topQueries.length - 1 ? { borderBottomWidth: 0 } : {},
                  ]}
                >
                  <Text style={s.queryText}>{q.query}</Text>
                  <Text style={s.clicksText}>{fmtNum(q.clicks)}</Text>
                  <Text style={s.imprText}>{fmtNum(q.impressions)}</Text>
                  <Text style={[s.ctrText, { color: isUnderperformer ? C.amber : C.body }]}>
                    {((q.clicks / Math.max(q.impressions, 1)) * 100).toFixed(1)}%
                  </Text>
                  <Text style={[s.posText, { color: posColor(q.position) }]}>
                    {q.position.toFixed(1)}
                  </Text>
                </View>
              );
            })}
          </View>
        </View>
      )}
    </View>
  );
}
