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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 6 },
  subtext: { ...S.small, marginBottom: 14 },
  table: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    overflow: "hidden",
  },
  headerRow: {
    flexDirection: "row",
    backgroundColor: C.surface,
    paddingHorizontal: 13,
    paddingVertical: 8,
    borderBottomWidth: 0.75,
    borderBottomColor: C.border,
  },
  row: {
    flexDirection: "row",
    paddingHorizontal: 13,
    paddingVertical: 9,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  sectionDivider: {
    flexDirection: "row",
    paddingHorizontal: 13,
    paddingVertical: 5,
    backgroundColor: C.surface,
    borderBottomWidth: 0.5,
    borderBottomColor: C.border,
  },
  sectionLabel: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  colSignal: { flex: 2.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  colValue: { flex: 1.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  colNote: { flex: 3, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  signalText: { flex: 2.5, fontSize: 10, color: C.ink },
  valueOk: { flex: 1.5, fontSize: 10, color: C.green, fontFamily: "Helvetica-Bold" },
  valueBad: { flex: 1.5, fontSize: 10, color: C.red, fontFamily: "Helvetica-Bold" },
  valueWarn: { flex: 1.5, fontSize: 10, color: C.amber, fontFamily: "Helvetica-Bold" },
  valueNeutral: { flex: 1.5, fontSize: 10, color: C.muted },
  noteText: { flex: 3, fontSize: 9.5, color: C.muted, lineHeight: 1.4 },
  // CWV sub-table
  cwvSection: { marginTop: 14 },
  cwvHeading: { ...S.label, marginBottom: 6 },
  cwvTable: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    overflow: "hidden",
  },
  cwvHeaderRow: {
    flexDirection: "row",
    backgroundColor: C.surface,
    paddingHorizontal: 13,
    paddingVertical: 7,
    borderBottomWidth: 0.75,
    borderBottomColor: C.border,
  },
  cwvRow: {
    flexDirection: "row",
    paddingHorizontal: 13,
    paddingVertical: 8,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  cwvColUrl: { flex: 3.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  cwvColMetric: { flex: 1.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  cwvUrlText: { flex: 3.5, fontSize: 8.5, color: C.accent },
  cwvGood: { flex: 1.5, fontSize: 9, color: C.green, fontFamily: "Helvetica-Bold" },
  cwvWarn: { flex: 1.5, fontSize: 9, color: C.amber, fontFamily: "Helvetica-Bold" },
  cwvBad: { flex: 1.5, fontSize: 9, color: C.red, fontFamily: "Helvetica-Bold" },
  cwvNa: { flex: 1.5, fontSize: 9, color: C.caption },
});

interface TechnicalMetrics {
  brokenLinksTotal?: number;
  schemaPercent?: number;
  nonIndexablePages?: number;
  redirectChainsCount?: number;
  missingTitles?: number;
  missingDescriptions?: number;
  missingH1?: number;
}

interface WebVitalRow {
  url: string;
  samples: number;
  lcp75?: number;
  cls75?: number;
  inp75?: number;
  ttfb75?: number;
}

interface RawData {
  pagesScanned?: number;
  summary?: {
    hasSitemap?: boolean;
    hasRobotsTxt?: boolean;
    mobileFriendly?: boolean | null;
    totalPages?: number;
  };
  technicalMetrics?: TechnicalMetrics;
  webVitalsSummary?: WebVitalRow[];
}

interface Props {
  rawData?: RawData | null;
}

type RowStyle =
  | typeof s.valueOk
  | typeof s.valueBad
  | typeof s.valueWarn
  | typeof s.valueNeutral;

function ok(v: boolean): { style: RowStyle; value: string } {
  return v ? { style: s.valueOk, value: "✓ Yes" } : { style: s.valueBad, value: "✗ No" };
}

function cwvStyle(rating: "good" | "warn" | "bad" | "na") {
  switch (rating) {
    case "good": return s.cwvGood;
    case "warn": return s.cwvWarn;
    case "bad": return s.cwvBad;
    default: return s.cwvNa;
  }
}

function lcpRating(ms?: number): "good" | "warn" | "bad" | "na" {
  if (ms == null) return "na";
  return ms < 2500 ? "good" : ms < 4000 ? "warn" : "bad";
}
function inpRating(ms?: number): "good" | "warn" | "bad" | "na" {
  if (ms == null) return "na";
  return ms < 200 ? "good" : ms < 500 ? "warn" : "bad";
}
function clsRating(v?: number): "good" | "warn" | "bad" | "na" {
  if (v == null) return "na";
  return v < 0.1 ? "good" : v < 0.25 ? "warn" : "bad";
}
function ttfbRating(ms?: number): "good" | "warn" | "bad" | "na" {
  if (ms == null) return "na";
  return ms < 800 ? "good" : ms < 1800 ? "warn" : "bad";
}

function fmtLcp(ms?: number) { return ms == null ? "—" : `${(ms / 1000).toFixed(2)}s`; }
function fmtMs(ms?: number) { return ms == null ? "—" : `${ms.toFixed(0)}ms`; }
function fmtCls(v?: number) { return v == null ? "—" : v.toFixed(3); }

export function TechnicalHealth({ rawData }: Props) {
  const summary = rawData?.summary;
  const tm = rawData?.technicalMetrics;
  const cwv = rawData?.webVitalsSummary;

  const sitemap = summary?.hasSitemap;
  const robots = summary?.hasRobotsTxt;
  const mobile = summary?.mobileFriendly;
  const broken = tm?.brokenLinksTotal;
  const schema = tm?.schemaPercent;
  const nonIndex = tm?.nonIndexablePages;
  const redirects = tm?.redirectChainsCount;
  const missingTitles = tm?.missingTitles;
  const missingDescs = tm?.missingDescriptions;
  const missingH1 = tm?.missingH1;

  if (!summary && !tm && !cwv) {
    return (
      <View>
        <Text style={s.heading}>Technical Health Diagnostics</Text>
        <Text style={s.subtext}>
          This audit was completed in telemetry mode — detailed crawl diagnostics are available when the site is accessible to the crawler.
        </Text>
      </View>
    );
  }

  const rows: Array<{ signal: string; value: string; style: RowStyle; note: string }> = [
    {
      signal: "XML Sitemap",
      ...ok(sitemap ?? false),
      note: sitemap
        ? "Sitemap present and accessible."
        : "No sitemap found — add at /sitemap.xml and submit in Search Console.",
    },
    {
      signal: "Robots.txt",
      ...ok(robots ?? false),
      note: robots
        ? "Robots.txt present."
        : "Missing robots.txt — add at /robots.txt to guide crawler access.",
    },
    {
      signal: "Mobile Rendering",
      value: mobile === true ? "✓ Yes" : mobile === false ? "✗ No" : "—",
      style: mobile === true ? s.valueOk : mobile === false ? s.valueBad : s.valueNeutral,
      note:
        mobile === true
          ? "Mobile usability signals detected."
          : mobile === false
          ? "Mobile usability issues found — review Core Web Vitals in Search Console."
          : "Mobile data unavailable for this crawl.",
    },
    {
      signal: "Missing Page Titles",
      value: missingTitles != null ? String(missingTitles) : "—",
      style: (missingTitles ?? 0) > 0 ? s.valueBad : s.valueOk,
      note:
        (missingTitles ?? 0) > 0
          ? `${missingTitles} page(s) missing title tags — add unique, descriptive titles under 60 characters.`
          : "All crawled pages have title tags.",
    },
    {
      signal: "Missing Meta Descriptions",
      value: missingDescs != null ? String(missingDescs) : "—",
      style: (missingDescs ?? 0) > 0 ? s.valueBad : s.valueOk,
      note:
        (missingDescs ?? 0) > 0
          ? `${missingDescs} page(s) missing meta descriptions — write 70-160 character summaries for each.`
          : "All crawled pages have meta descriptions.",
    },
    {
      signal: "Missing H1 Headings",
      value: missingH1 != null ? String(missingH1) : "—",
      style: (missingH1 ?? 0) > 0 ? s.valueBad : s.valueOk,
      note:
        (missingH1 ?? 0) > 0
          ? `${missingH1} page(s) missing H1 — add a single H1 per page that matches primary keyword intent.`
          : "All crawled pages have H1 headings.",
    },
    {
      signal: "Broken Internal Links",
      value: broken != null ? String(broken) : "—",
      style: (broken ?? 0) > 0 ? s.valueBad : s.valueOk,
      note:
        (broken ?? 0) > 0
          ? `${broken} broken link(s) found — fix or redirect to preserve link equity.`
          : "No broken internal links detected.",
    },
    {
      signal: "Schema Markup Coverage",
      value: schema != null ? `${schema.toFixed(0)}%` : "—",
      style: schema == null ? s.valueNeutral : schema >= 50 ? s.valueOk : schema >= 25 ? s.valueWarn : s.valueBad,
      note:
        schema == null
          ? "Schema data unavailable."
          : schema >= 50
          ? "Schema markup present across key pages."
          : "Low schema coverage — implement Organization, LocalBusiness, or Article schema on priority pages.",
    },
    {
      signal: "Non-Indexable Pages",
      value: nonIndex != null ? String(nonIndex) : "—",
      style: (nonIndex ?? 0) > 0 ? s.valueBad : s.valueOk,
      note:
        (nonIndex ?? 0) > 0
          ? `${nonIndex} page(s) blocked from indexing — audit robots meta tags and noindex directives.`
          : "All crawled pages are indexable.",
    },
    {
      signal: "Redirect Chains",
      value: redirects != null ? String(redirects) : "—",
      style: (redirects ?? 0) > 0 ? s.valueBad : s.valueOk,
      note:
        (redirects ?? 0) > 0
          ? `${redirects} redirect chain(s) detected — consolidate to direct 301s.`
          : "No redirect chains detected.",
    },
  ];

  return (
    <View>
      <Text style={s.heading}>Technical Health Diagnostics</Text>
      <Text style={s.subtext}>Structural signals from the site crawl.</Text>
      <View style={s.table}>
        <View style={s.headerRow}>
          <Text style={s.colSignal}>SIGNAL</Text>
          <Text style={s.colValue}>STATUS</Text>
          <Text style={s.colNote}>DETAIL</Text>
        </View>
        {rows.map((r, i) => (
          <View key={i} style={[s.row, i === rows.length - 1 ? { borderBottomWidth: 0 } : {}]}>
            <Text style={s.signalText}>{r.signal}</Text>
            <Text style={r.style}>{r.value}</Text>
            <Text style={s.noteText}>{r.note}</Text>
          </View>
        ))}
      </View>

      {cwv && cwv.length > 0 && (
        <View style={s.cwvSection}>
          <Text style={s.cwvHeading}>Core Web Vitals (p75 by URL, real user data)</Text>
          <View style={s.cwvTable}>
            <View style={s.cwvHeaderRow}>
              <Text style={s.cwvColUrl}>URL</Text>
              <Text style={s.cwvColMetric}>LCP</Text>
              <Text style={s.cwvColMetric}>INP</Text>
              <Text style={s.cwvColMetric}>CLS</Text>
              <Text style={s.cwvColMetric}>TTFB</Text>
            </View>
            {cwv.slice(0, 12).map((row, i) => (
              <View key={i} style={[s.cwvRow, i === Math.min(cwv.length, 12) - 1 ? { borderBottomWidth: 0 } : {}]}>
                <Text style={s.cwvUrlText}>{row.url}</Text>
                <Text style={cwvStyle(lcpRating(row.lcp75))}>{fmtLcp(row.lcp75)}</Text>
                <Text style={cwvStyle(inpRating(row.inp75))}>{fmtMs(row.inp75)}</Text>
                <Text style={cwvStyle(clsRating(row.cls75))}>{fmtCls(row.cls75)}</Text>
                <Text style={cwvStyle(ttfbRating(row.ttfb75))}>{fmtMs(row.ttfb75)}</Text>
              </View>
            ))}
          </View>
        </View>
      )}
    </View>
  );
}
