import { View, Text, StyleSheet } from "@react-pdf/renderer";
import { C, S } from "../styles";
import type { BilingualAudit } 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: 18 },
  pillText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.8 },
  // Section blocks
  sectionBlock: { marginBottom: 22 },
  sectionHeading: { fontSize: 11, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 6, lineHeight: 1.3 },
  // Table
  table: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, overflow: "hidden", marginBottom: 10 },
  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: "flex-start",
  },
  rowAlt: { backgroundColor: "#fafafa" },
  colHeader: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  cellText: { fontSize: 9, color: C.body, lineHeight: 1.4 },
  cellMuted: { fontSize: 8, color: C.muted, lineHeight: 1.4 },
  // Status labels
  statusGood: { fontSize: 8, color: C.green, fontFamily: "Helvetica-Bold" },
  statusWarn: { fontSize: 8, color: C.amber, fontFamily: "Helvetica-Bold" },
  statusBad: { fontSize: 8, color: C.red, fontFamily: "Helvetica-Bold" },
  // Progress bar track
  track: { height: 5, backgroundColor: "#e5e7eb", borderRadius: 3, overflow: "hidden", marginTop: 3, marginBottom: 8 },
  fill: { height: 5, borderRadius: 3 },
  // Bug card
  bugCard: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 10,
    marginBottom: 6,
    backgroundColor: C.surface,
  },
  bugText: { fontSize: 9, color: C.body, lineHeight: 1.5 },
  bugMono: { fontSize: 7.5, color: C.muted, fontFamily: "Helvetica", marginTop: 2 },
  // Divider
  divider: { borderTopWidth: 0.75, borderTopColor: C.border, marginVertical: 14 },
  footnote: { ...S.caption, lineHeight: 1.55 },
});

// ─── Helpers ──────────────────────────────────────────────────────────────────

function urlPath(url: string): string {
  try {
    const path = new URL(url).pathname || "/";
    return path.length > 52 ? path.slice(0, 51) + "…" : path;
  } catch {
    return url.length > 52 ? url.slice(0, 51) + "…" : url;
  }
}

function pct(n: number): string {
  return `${n.toFixed(1)}%`;
}

function langName(ba: BilingualAudit, code: string): string {
  return ba.detectedLanguages.find((d) => d.code === code)?.displayName ?? code.toUpperCase();
}

function parityStyle(p: number) {
  return p >= 80 ? s.statusGood : p >= 50 ? s.statusWarn : s.statusBad;
}

function fillColor(p: number): string {
  return p >= 80 ? C.green : p >= 50 ? C.amber : C.red;
}

// ─── Sub-section A: Language Coverage ────────────────────────────────────────

function LanguageCoverageBlock({ ba }: { ba: BilingualAudit }) {
  return (
    <View style={s.sectionBlock} wrap={false}>
      <Text style={s.sectionHeading}>Language Coverage</Text>
      <View style={s.table}>
        <View style={s.headerRow}>
          <Text style={[s.colHeader, { flex: 3 }]}>Language</Text>
          <Text style={[s.colHeader, { flex: 1, textAlign: "right" }]}>Pages</Text>
          <Text style={[s.colHeader, { flex: 1, textAlign: "right" }]}>Share</Text>
          <Text style={[s.colHeader, { flex: 1.5, textAlign: "right" }]}>Role</Text>
        </View>
        {ba.languageCoverage.perLanguage.map((lang, i) => (
          <View key={lang.code} style={[s.tableRow, i % 2 === 1 ? s.rowAlt : {}]}>
            <Text style={[s.cellText, { flex: 3 }]}>{langName(ba, lang.code)}</Text>
            <Text style={[s.cellText, { flex: 1, textAlign: "right" }]}>{lang.pageCount.toLocaleString()}</Text>
            <Text style={[s.cellText, { flex: 1, textAlign: "right" }]}>{pct(lang.sharePercent)}</Text>
            <Text style={[s.cellMuted, { flex: 1.5, textAlign: "right" }]}>
              {lang.code === ba.primaryLanguage ? "Primary" : "Secondary"}
            </Text>
          </View>
        ))}
      </View>
    </View>
  );
}

// ─── Sub-section B: Content Parity ───────────────────────────────────────────

function ContentParityBlock({ ba }: { ba: BilingualAudit }) {
  const langs = ba.contentParity.perNonPrimaryLanguage;
  if (langs.length === 0) return null;
  return (
    <View style={s.sectionBlock} wrap={false}>
      <Text style={s.sectionHeading}>Content Parity</Text>
      {langs.map((lang) => (
        <View key={lang.code} style={{ marginBottom: 12 }}>
          <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
            <Text style={s.cellText}>{langName(ba, lang.code)}</Text>
            <Text style={parityStyle(lang.parityPercent)}>{pct(lang.parityPercent)} equivalent</Text>
          </View>
          <View style={s.track}>
            <View style={[s.fill, { width: `${Math.min(100, lang.parityPercent)}%`, backgroundColor: fillColor(lang.parityPercent) }]} />
          </View>
          <View style={{ flexDirection: "row", gap: 14 }}>
            <Text style={s.cellMuted}>{lang.pagesWithEquivalent} equivalent pages</Text>
            <Text style={[s.cellMuted, lang.pagesMissingEquivalent > 0 ? { color: C.red } : {}]}>
              {lang.pagesMissingEquivalent} missing
            </Text>
          </View>
          {lang.topMissingPages.length > 0 && (
            <View style={{ marginTop: 6 }}>
              <Text style={[s.colHeader, { marginBottom: 3 }]}>Top missing pages</Text>
              {lang.topMissingPages.slice(0, 4).map((p, i) => (
                <Text key={i} style={s.bugMono}>
                  {urlPath(p.primaryUrl)} → {urlPath(p.expectedNonPrimaryUrl)}
                </Text>
              ))}
            </View>
          )}
        </View>
      ))}
    </View>
  );
}

// ─── Sub-section C: Hreflang ──────────────────────────────────────────────────

function HreflangBlock({ ba }: { ba: BilingualAudit }) {
  const h = ba.hreflangImplementation;
  const statusStyle =
    h.status === "complete" ? s.statusGood : h.status === "partial" ? s.statusWarn : s.statusBad;
  const statusLabel =
    h.status === "complete" ? "Complete" : h.status === "partial" ? "Partial" : "Not Detected";
  return (
    <View style={s.sectionBlock} wrap={false}>
      <Text style={s.sectionHeading}>Hreflang Implementation</Text>
      <View style={{ flexDirection: "row", gap: 24, marginBottom: 10 }}>
        <View>
          <Text style={statusStyle}>{statusLabel}</Text>
          <Text style={s.cellMuted}>{pct(h.coveragePercent)} page coverage</Text>
        </View>
        <View>
          <Text style={s.cellText}>{h.pagesWithHreflang} pages with hreflang</Text>
          <Text style={s.cellMuted}>~{h.pagesShouldHaveHreflang} pages needed</Text>
        </View>
        {h.bidirectionalCheckPassed != null && (
          <View>
            <Text style={h.bidirectionalCheckPassed ? s.statusGood : s.statusBad}>
              Bidirectional: {h.bidirectionalCheckPassed ? "Passed" : "Failed"}
            </Text>
          </View>
        )}
      </View>
      {h.commonBugs.map((bug, i) => (
        <View key={i} style={s.bugCard}>
          <Text style={s.bugText}>{bug.description}</Text>
          {bug.affectedUrls.length > 0 && (
            <Text style={s.bugMono}>e.g. {urlPath(bug.affectedUrls[0])}{bug.affectedUrls.length > 1 ? ` +${bug.affectedUrls.length - 1} more` : ""}</Text>
          )}
        </View>
      ))}
    </View>
  );
}

// ─── Sub-section D: Conversion Pathway ───────────────────────────────────────

function ConversionPathwayBlock({ ba }: { ba: BilingualAudit }) {
  const cp = ba.conversionPathway;
  if (!cp || cp.perLanguage.length === 0) return null;
  return (
    <View style={s.sectionBlock} wrap={false}>
      <Text style={s.sectionHeading}>Conversion by Language Segment (30 days)</Text>
      <View style={s.table}>
        <View style={s.headerRow}>
          <Text style={[s.colHeader, { flex: 3 }]}>Language</Text>
          <Text style={[s.colHeader, { flex: 2, textAlign: "right" }]}>Sessions</Text>
          <Text style={[s.colHeader, { flex: 2, textAlign: "right" }]}>Conversions</Text>
          <Text style={[s.colHeader, { flex: 2, textAlign: "right" }]}>Rate</Text>
        </View>
        {cp.perLanguage.map((lang, i) => {
          const rateStyle =
            lang.conversionRate >= 3 ? s.statusGood : lang.conversionRate >= 1 ? s.statusWarn : s.cellMuted;
          return (
            <View key={lang.code} style={[s.tableRow, i % 2 === 1 ? s.rowAlt : {}]}>
              <Text style={[s.cellText, { flex: 3 }]}>{langName(ba, lang.code)}</Text>
              <Text style={[s.cellText, { flex: 2, textAlign: "right" }]}>{lang.sessions.toLocaleString()}</Text>
              <Text style={[s.cellText, { flex: 2, textAlign: "right" }]}>{lang.conversions.toLocaleString()}</Text>
              <Text style={[rateStyle, { flex: 2, textAlign: "right" }]}>{pct(lang.conversionRate)}</Text>
            </View>
          );
        })}
      </View>
    </View>
  );
}

// ─── Sub-section E: AI Citation ───────────────────────────────────────────────

function AiCitationBlock({ ba }: { ba: BilingualAudit }) {
  const ac = ba.aiCitationByLanguage;
  if (!ac || ac.perLanguage.length === 0) return null;
  return (
    <View style={s.sectionBlock} wrap={false}>
      <Text style={s.sectionHeading}>AI Citation by Language</Text>
      <View style={s.table}>
        <View style={s.headerRow}>
          <Text style={[s.colHeader, { flex: 3 }]}>Language</Text>
          <Text style={[s.colHeader, { flex: 2, textAlign: "right" }]}>AI Visits</Text>
          <Text style={[s.colHeader, { flex: 2, textAlign: "right" }]}>Share of AI Traffic</Text>
        </View>
        {ac.perLanguage.map((lang, i) => (
          <View key={lang.code} style={[s.tableRow, i % 2 === 1 ? s.rowAlt : {}]}>
            <Text style={[s.cellText, { flex: 3 }]}>{langName(ba, lang.code)}</Text>
            <Text style={[s.cellText, { flex: 2, textAlign: "right" }]}>{lang.aiVisits.toLocaleString()}</Text>
            <Text style={[s.cellText, { flex: 2, textAlign: "right" }]}>{pct(lang.sharePercent)}</Text>
          </View>
        ))}
      </View>
    </View>
  );
}

// ─── Sub-section F: Content Quality ──────────────────────────────────────────

function ContentQualityBlock({ ba }: { ba: BilingualAudit }) {
  const langs = ba.contentQuality.perNonPrimaryLanguage;
  if (langs.length === 0) return null;
  return (
    <View style={s.sectionBlock} wrap={false}>
      <Text style={s.sectionHeading}>Content Depth & Call-to-Action Coverage</Text>
      <View style={s.table}>
        <View style={s.headerRow}>
          <Text style={[s.colHeader, { flex: 3 }]}>Language</Text>
          <Text style={[s.colHeader, { flex: 2, textAlign: "right" }]}>Avg Words</Text>
          <Text style={[s.colHeader, { flex: 2, textAlign: "right" }]}>Depth Ratio</Text>
          <Text style={[s.colHeader, { flex: 2, textAlign: "right" }]}>CTAs</Text>
        </View>
        {langs.map((lang, i) => {
          const ctaStyle =
            lang.bilingualCtaStatus === "present"
              ? s.statusGood
              : lang.bilingualCtaStatus === "partial"
                ? s.statusWarn
                : s.statusBad;
          const ctaLabel =
            lang.bilingualCtaStatus === "present"
              ? "Present"
              : lang.bilingualCtaStatus === "partial"
                ? "Partial"
                : "Absent";
          const depthStyle =
            lang.depthRatio >= 0.9 ? s.statusGood : lang.depthRatio >= 0.6 ? s.statusWarn : s.statusBad;
          return (
            <View key={lang.code} style={[s.tableRow, i % 2 === 1 ? s.rowAlt : {}]}>
              <Text style={[s.cellText, { flex: 3 }]}>{langName(ba, lang.code)}</Text>
              <Text style={[s.cellText, { flex: 2, textAlign: "right" }]}>{lang.avgWordCount.toLocaleString()}</Text>
              <Text style={[depthStyle, { flex: 2, textAlign: "right" }]}>{lang.depthRatio.toFixed(2)}×</Text>
              <Text style={[ctaStyle, { flex: 2, textAlign: "right" }]}>{ctaLabel}</Text>
            </View>
          );
        })}
      </View>
      {langs.some((l) => l.bilingualCtaRecommendation && l.bilingualCtaStatus !== "present") && (
        <View style={{ marginTop: 6 }}>
          {langs
            .filter((l) => l.bilingualCtaStatus !== "present")
            .map((lang) => (
              <Text key={lang.code} style={[s.footnote, { marginBottom: 4 }]}>
                {langName(ba, lang.code)}: {lang.bilingualCtaRecommendation}
              </Text>
            ))}
        </View>
      )}
    </View>
  );
}

// ─── Main export ──────────────────────────────────────────────────────────────

interface Props {
  bilingualAudit: BilingualAudit;
}

export function BilingualContentPage({ bilingualAudit: ba }: Props) {
  const conf = ba.dataConfidence;
  const confColor =
    conf === "high" ? C.green : conf === "moderate" ? C.amber : C.muted;
  const confLabel =
    conf === "high" ? "High confidence" : conf === "moderate" ? "Moderate confidence" : "Limited data";
  const nonPrimary = ba.detectedLanguages.filter((l) => l.code !== ba.primaryLanguage);

  return (
    <View>
      <Text style={s.heading}>Multi-Language Presence</Text>
      <Text style={s.subtext}>
        {langName(ba, ba.primaryLanguage)} primary ·{" "}
        {nonPrimary.map((l) => l.displayName || l.code.toUpperCase()).join(", ")}{" "}
        {nonPrimary.length === 1 ? "audience" : "audiences"} detected across the domain.
      </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>

      <LanguageCoverageBlock ba={ba} />
      <ContentParityBlock ba={ba} />
      <HreflangBlock ba={ba} />
      <ConversionPathwayBlock ba={ba} />
      <AiCitationBlock ba={ba} />
      <ContentQualityBlock ba={ba} />
    </View>
  );
}
