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: { ...S.small, marginBottom: 14 },
  // Table
  table: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    overflow: "hidden",
    marginBottom: 10,
  },
  headerRow: {
    flexDirection: "row",
    backgroundColor: C.surface,
    paddingHorizontal: 10,
    paddingVertical: 7,
    borderBottomWidth: 0.75,
    borderBottomColor: C.border,
  },
  row: {
    flexDirection: "row",
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  rowAlt: { backgroundColor: "#fafafa" },
  // 1st-party columns
  col1Url: { flex: 3.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  col1Visits: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  col1Conv: { flex: 1, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  col1Bounce: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  col1Session: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  col1Issues: { flex: 2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  // 3rd-party columns
  col3Url: { flex: 3.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  col3Words: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  col3H1: { flex: 0.8, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "center" },
  col3Meta: { flex: 0.8, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "center" },
  col3Schema: { flex: 1.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  col3Issues: { flex: 2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  // Cell text
  urlText: { fontSize: 8, color: C.accent, lineHeight: 1.3 },
  numText: { fontSize: 8.5, color: C.body, textAlign: "right" },
  numGreen: { fontSize: 8.5, color: C.green, fontFamily: "Helvetica-Bold", textAlign: "right" },
  checkOk: { fontSize: 8.5, color: C.green, textAlign: "center" },
  checkFail: { fontSize: 8.5, color: C.red, textAlign: "center" },
  schemaText: { fontSize: 8, color: C.muted, lineHeight: 1.3 },
  issueText: { fontSize: 7.5, color: C.amber, lineHeight: 1.3 },
  footer: { ...S.caption, marginTop: 8, lineHeight: 1.5 },
  // Site-wide stat strip
  statStrip: {
    flexDirection: "row",
    gap: 10,
    marginBottom: 14,
  },
  statBox: {
    flex: 1,
    backgroundColor: C.surface,
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 10,
    alignItems: "center",
  },
  statNum: { fontSize: 20, fontFamily: "Helvetica-Bold", color: C.ink, lineHeight: 1 },
  statLabel: { fontSize: 7.5, color: C.muted, textAlign: "center", marginTop: 3, letterSpacing: 0.5, textTransform: "uppercase" },
  selectionNote: { ...S.caption, marginTop: 6, marginBottom: 14, lineHeight: 1.5 },
});

interface PageRow {
  url: string;
  wordCount?: number;
  hasH1?: boolean;
  hasMetaDesc?: boolean;
  schemaTypes?: string[];
  issues?: string[];
  aiVisits?: number;
  conversions?: number;
}

interface RawPageEntry {
  url: string;
  wordCount?: number;
  h1?: string;
  metaDescription?: string;
  schemaTypes?: string[];
  isIndexable?: boolean;
}

interface Props {
  seo: SeoSection;
  isFirstParty: boolean;
  rawPages?: RawPageEntry[];
  totalPagesCrawled?: number;
  pagesScanned?: number;
}

function buildIssues(page: RawPageEntry): string[] {
  const issues: string[] = [];
  if (!page.h1) issues.push("Missing H1");
  if (!page.metaDescription) issues.push("Missing meta");
  if (!page.schemaTypes?.length) issues.push("No schema");
  if ((page.wordCount ?? 0) < 300) issues.push("Thin content");
  return issues;
}

export function PagesAnalyzedPage({ seo, isFirstParty, rawPages, totalPagesCrawled, pagesScanned }: Props) {
  const aiPages = seo.aiConversionAttribution?.topConvertingPages ?? [];
  const attributionPages = seo.aiSearchPerformance?.topAttributedPages ?? [];

  // Build rows
  let rows: PageRow[] = [];

  if (isFirstParty && (aiPages.length > 0 || attributionPages.length > 0)) {
    // 1st-party: derive from AI attribution data
    const aiMap = new Map(aiPages.map((p) => [p.url, p]));
    const attrMap = new Map(attributionPages.map((p) => [p.url, p]));
    const allUrls = Array.from(new Set([...aiMap.keys(), ...attrMap.keys()])).slice(0, 20);
    rows = allUrls.map((url) => {
      const ai = aiMap.get(url);
      const attr = attrMap.get(url);
      const raw = rawPages?.find((p) => p.url === url);
      return {
        url,
        aiVisits: ai?.aiVisits ?? attr?.aiVisits ?? 0,
        conversions: ai?.conversions ?? attr?.conversions ?? 0,
        wordCount: raw?.wordCount,
        hasH1: raw ? !!raw.h1 : undefined,
        hasMetaDesc: raw ? !!raw.metaDescription : undefined,
        schemaTypes: raw?.schemaTypes,
        issues: raw ? buildIssues(raw as Parameters<typeof buildIssues>[0]) : [],
      };
    }).sort((a, b) => (b.aiVisits ?? 0) - (a.aiVisits ?? 0));
  } else if (rawPages && rawPages.length > 0) {
    // 3rd-party: derive from crawl
    rows = rawPages.slice(0, 20).map((p) => ({
      url: p.url,
      wordCount: p.wordCount,
      hasH1: !!p.h1,
      hasMetaDesc: !!p.metaDescription,
      schemaTypes: p.schemaTypes,
      issues: buildIssues(p as Parameters<typeof buildIssues>[0]),
    }));
  }

  if (rows.length === 0) return null;

  const totalCrawled = totalPagesCrawled ?? pagesScanned ?? rawPages?.length ?? rows.length;
  const deepReviewedCount = rows.length;
  const sortBy = isFirstParty ? "AI referrals" : "sitemap priority";

  return (
    <View>
      <Text style={s.heading}>Pages Deeply Reviewed</Text>
      <Text style={s.subheading}>
        Representative pages selected for in-depth semantic analysis. Site-wide signals were assessed across all crawled URLs and are summarized in the Technical Health section above.
      </Text>

      {/* Site-wide analysis stat strip */}
      <View style={s.statStrip}>
        {totalCrawled != null && (
          <View style={s.statBox}>
            <Text style={s.statNum}>{totalCrawled}</Text>
            <Text style={s.statLabel}>Pages Crawled</Text>
          </View>
        )}
        {pagesScanned != null && pagesScanned !== totalCrawled && (
          <View style={s.statBox}>
            <Text style={s.statNum}>{pagesScanned}</Text>
            <Text style={s.statLabel}>Pages Scanned</Text>
          </View>
        )}
        <View style={s.statBox}>
          <Text style={s.statNum}>{deepReviewedCount}</Text>
          <Text style={s.statLabel}>Deep-Reviewed</Text>
        </View>
        {pagesScanned != null && (
          <View style={s.statBox}>
            <Text style={s.statNum}>{pagesScanned * 8}+</Text>
            <Text style={s.statLabel}>Signals Assessed</Text>
          </View>
        )}
      </View>

      <Text style={s.selectionNote}>
        Page selection prioritizes commercially important URLs (homepage, about, services, contact) and high-value pages from sitemap analysis.
      </Text>

      {/* Render in chunks of 10 to allow clean page breaks */}
      {[rows.slice(0, 10), rows.slice(10, 20)].map((chunk, chunkIdx) => {
        if (chunk.length === 0) return null;
        return (
          <View key={chunkIdx} break={chunkIdx > 0}>
            <View style={s.table}>
              {chunkIdx === 0 && (
                <View style={s.headerRow}>
                  {isFirstParty ? (
                    <>
                      <Text style={s.col1Url}>URL</Text>
                      <Text style={s.col1Visits}>AI VISITS</Text>
                      <Text style={s.col1Conv}>CONV.</Text>
                      <Text style={s.col1Issues}>ISSUES</Text>
                    </>
                  ) : (
                    <>
                      <Text style={s.col3Url}>URL</Text>
                      <Text style={s.col3Words}>WORDS</Text>
                      <Text style={s.col3H1}>H1</Text>
                      <Text style={s.col3Meta}>META</Text>
                      <Text style={s.col3Schema}>SCHEMA</Text>
                      <Text style={s.col3Issues}>ISSUES</Text>
                    </>
                  )}
                </View>
              )}
              {chunk.map((row, i) => (
                <View
                  key={i}
                  style={[s.row, i % 2 === 1 ? s.rowAlt : {}, i === chunk.length - 1 ? { borderBottomWidth: 0 } : {}]}
                >
                  {isFirstParty ? (
                    <>
                      <Text style={[s.urlText, { flex: 3.5 }]}>{row.url}</Text>
                      <Text style={[s.numText, { flex: 1.2 }]}>{row.aiVisits ?? "—"}</Text>
                      <Text style={[(row.conversions ?? 0) > 0 ? s.numGreen : s.numText, { flex: 1 }]}>{row.conversions ?? "—"}</Text>
                      <Text style={[s.issueText, { flex: 2 }]}>{(row.issues ?? []).join(", ") || "—"}</Text>
                    </>
                  ) : (
                    <>
                      <Text style={[s.urlText, { flex: 3.5 }]}>{row.url}</Text>
                      <Text style={[s.numText, { flex: 1.2 }]}>{row.wordCount ?? "—"}</Text>
                      <Text style={row.hasH1 === true ? s.checkOk : row.hasH1 === false ? s.checkFail : [s.numText, { flex: 0.8 }]}>
                        {row.hasH1 === true ? "✓" : row.hasH1 === false ? "✗" : "—"}
                      </Text>
                      <Text style={row.hasMetaDesc === true ? s.checkOk : row.hasMetaDesc === false ? s.checkFail : [s.numText, { flex: 0.8 }]}>
                        {row.hasMetaDesc === true ? "✓" : row.hasMetaDesc === false ? "✗" : "—"}
                      </Text>
                      <Text style={[s.schemaText, { flex: 1.5 }]}>
                        {row.schemaTypes && row.schemaTypes.length > 0 ? row.schemaTypes.join(", ") : "None"}
                      </Text>
                      <Text style={[s.issueText, { flex: 2 }]}>{(row.issues ?? []).join(", ") || "—"}</Text>
                    </>
                  )}
                </View>
              ))}
            </View>
          </View>
        );
      })}

      <Text style={s.footer}>
        {`Site-wide analysis covered ${totalCrawled} page${totalCrawled !== 1 ? "s" : ""}. The ${rows.length} pages above were selected for deep semantic review by ${sortBy}; all crawled pages contributed to the Technical SEO and scoring calculations.`}
      </Text>
    </View>
  );
}
