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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, marginBottom: 16, color: C.muted },
  section: { marginBottom: 14 },
  sectionHeading: { fontSize: 10, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 8 },
  // Stat tiles
  statRow: { flexDirection: "row", gap: 8, marginBottom: 14 },
  statTile: { flex: 1, borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8, alignItems: "center" },
  statValue: { fontSize: 16, fontFamily: "Helvetica-Bold" },
  statLabel: { fontSize: 7, color: C.muted, marginTop: 2, textAlign: "center" },
  // Bar chart rows
  barRow: { flexDirection: "row", alignItems: "center", gap: 6, marginBottom: 5 },
  barLabel: { fontSize: 8, color: C.body, width: 130 },
  barTrack: { flex: 1, height: 8, backgroundColor: "#f1f5f9", borderRadius: 3, overflow: "hidden" },
  barFill: { height: 8, borderRadius: 3 },
  barPct: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.ink, width: 30, textAlign: "right" },
  // Engine table
  table: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, overflow: "hidden", marginBottom: 12 },
  headerRow: { flexDirection: "row", backgroundColor: C.surface, paddingHorizontal: 8, paddingVertical: 5, borderBottomWidth: 0.75, borderBottomColor: C.border },
  tableRow: { flexDirection: "row", paddingHorizontal: 8, paddingVertical: 5, borderBottomWidth: 0.5, borderBottomColor: "#f1f5f9" },
  rowAlt: { backgroundColor: "#fafafa" },
  colHeader: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.5 },
  cellText: { fontSize: 8, color: C.body },
  cellMuted: { fontSize: 7, color: C.muted },
  cellBold: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.ink },
  // Citation table
  citRow: { flexDirection: "row", alignItems: "center", gap: 6, paddingVertical: 3, borderBottomWidth: 0.5, borderBottomColor: "#f1f5f9" },
  citDomain: { flex: 1, fontSize: 8, fontFamily: "Courier", color: C.body },
  citBadge: { borderRadius: 3, paddingHorizontal: 5, paddingVertical: 1.5 },
  citBadgeText: { fontSize: 6.5, fontFamily: "Helvetica-Bold" },
  citCount: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.ink, width: 24, textAlign: "right" },
  // Insights
  insightBlock: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 9, marginBottom: 6, backgroundColor: "#eef2ff" },
  insightText: { fontSize: 8.5, color: "#3730a3", lineHeight: 1.4 },
  // Patent
  patent: { fontSize: 7.5, color: C.muted, fontStyle: "italic", marginTop: 10 },
});

function mentionColor(rate: number): string {
  if (rate >= 0.6) return "#059669";
  if (rate >= 0.3) return "#d97706";
  return "#dc2626";
}

function barColor(rate: number): string {
  if (rate >= 0.5) return "#10b981";
  if (rate >= 0.25) return "#f59e0b";
  return "#ef4444";
}

export function AiSearchVerificationPage({
  aiSearchVerification,
}: {
  aiSearchVerification: AiSearchVerification;
}) {
  const asv = aiSearchVerification;
  const v = asv.brandVisibility;
  const pct = (r: number) => `${Math.round(r * 100)}%`;

  const queryTypeRows = [
    { label: "Branded queries", rate: v.brandedQueryMentionRate },
    { label: "Non-branded national", rate: v.nonBrandedMentionRate },
    { label: "Local / geo-targeted", rate: v.localQueryMentionRate },
    { label: "Informational long-tail", rate: v.informationalMentionRate },
  ];

  return (
    <View wrap={false}>
      <Text style={s.heading}>AI Search Engine Visibility</Text>
      <Text style={s.subheading}>
        Live verification across {asv.engineSummaries.length} AI search platforms —{" "}
        {asv.queriesChecked} queries checked
        {asv.degraded ? " (partial results — some engines unavailable)" : ""}
      </Text>

      {/* Overall stat tiles */}
      <View style={s.statRow}>
        {[
          { label: "Overall mention rate", value: pct(v.overallMentionRate), color: mentionColor(v.overallMentionRate) },
          { label: "Citation rate", value: pct(v.overallCitationRate), color: "#4f46e5" },
          { label: "Branded queries", value: pct(v.brandedQueryMentionRate), color: mentionColor(v.brandedQueryMentionRate) },
          { label: "Non-branded queries", value: pct(v.nonBrandedMentionRate), color: mentionColor(v.nonBrandedMentionRate) },
        ].map(({ label, value, color }) => (
          <View key={label} style={s.statTile}>
            <Text style={[s.statValue, { color }]}>{value}</Text>
            <Text style={s.statLabel}>{label}</Text>
          </View>
        ))}
      </View>

      {/* Query type breakdown */}
      <View style={s.section}>
        <Text style={s.sectionHeading}>Visibility by query type</Text>
        {queryTypeRows.map(({ label, rate }) => (
          <View key={label} style={s.barRow}>
            <Text style={s.barLabel}>{label}</Text>
            <View style={s.barTrack}>
              <View style={[s.barFill, { width: `${Math.round(rate * 100)}%`, backgroundColor: barColor(rate) }]} />
            </View>
            <Text style={s.barPct}>{pct(rate)}</Text>
          </View>
        ))}
      </View>

      {/* Engine summary table */}
      <View style={s.section}>
        <Text style={s.sectionHeading}>Results by AI engine</Text>
        <View style={s.table}>
          <View style={s.headerRow}>
            <Text style={[s.colHeader, { flex: 2 }]}>ENGINE</Text>
            <Text style={[s.colHeader, { flex: 1 }]}>MENTION</Text>
            <Text style={[s.colHeader, { flex: 1 }]}>CITATION</Text>
            <Text style={[s.colHeader, { flex: 1 }]}>AVG POS</Text>
            <Text style={[s.colHeader, { flex: 1 }]}>SUCCESS</Text>
          </View>
          {asv.engineSummaries
            .sort((a, b) => b.brandMentionRate - a.brandMentionRate)
            .map((s_row, i) => (
              <View key={s_row.engineInternalName} style={[s.tableRow, i % 2 === 1 ? s.rowAlt : {}]}>
                <View style={{ flex: 2 }}>
                  <Text style={s.cellBold}>{s_row.engineDisplayName}</Text>
                  <Text style={s.cellMuted}>{s_row.engineSubtitle}</Text>
                </View>
                <Text style={[s.cellBold, { flex: 1, color: mentionColor(s_row.brandMentionRate) }]}>
                  {pct(s_row.brandMentionRate)}
                </Text>
                <Text style={[s.cellText, { flex: 1 }]}>{pct(s_row.brandCitationRate)}</Text>
                <Text style={[s.cellText, { flex: 1 }]}>
                  {s_row.avgPositionWhenMentioned !== null
                    ? `#${s_row.avgPositionWhenMentioned.toFixed(1)}`
                    : "—"}
                </Text>
                <Text style={[s.cellText, { flex: 1 }]}>{pct(s_row.successRate)}</Text>
              </View>
            ))}
        </View>
      </View>

      {/* Top citations */}
      {asv.topCitations.length > 0 && (
        <View style={s.section}>
          <Text style={s.sectionHeading}>Most-cited domains</Text>
          <View style={s.table}>
            {asv.topCitations.slice(0, 8).map((c, i) => {
              const badgeBg = c.isBrandDomain ? "#e0e7ff" : c.isCompetitorDomain ? "#fee2e2" : "#f1f5f9";
              const badgeFg = c.isBrandDomain ? "#4338ca" : c.isCompetitorDomain ? "#b91c1c" : "#64748b";
              return (
                <View key={c.domain} style={[s.citRow, { paddingHorizontal: 8 }, i % 2 === 1 ? { backgroundColor: "#fafafa" } : {}]}>
                  <View style={[s.citBadge, { backgroundColor: badgeBg }]}>
                    <Text style={[s.citBadgeText, { color: badgeFg }]}>
                      {c.isBrandDomain ? "brand" : c.isCompetitorDomain ? "competitor" : "other"}
                    </Text>
                  </View>
                  <Text style={s.citDomain}>{c.domain}</Text>
                  <Text style={s.citCount}>{c.citationCount}×</Text>
                </View>
              );
            })}
          </View>
        </View>
      )}

      {/* Insights */}
      {asv.insights.length > 0 && (
        <View style={s.section}>
          <Text style={s.sectionHeading}>Key findings</Text>
          {asv.insights.map((ins, i) => (
            <View key={i} style={s.insightBlock}>
              <Text style={s.insightText}>{i + 1}. {ins}</Text>
            </View>
          ))}
        </View>
      )}

      <Text style={s.patent}>
        meSEO AI Search Verification: Live probes across major AI search platforms using meSEO&apos;s proprietary
        query categorization engine. Results reflect real-time AI-generated responses and citation patterns.
      </Text>
    </View>
  );
}
