import { View, Text, StyleSheet } from "@react-pdf/renderer";
import { C, S } from "../styles";
import type { SnippetCaptureStrategy, CapturedSnippetReformulation, SnippetType } from "../../../snippet-capture/types";

const SNIPPET_TYPE_LABELS: Record<SnippetType, string> = {
  paragraph: "Paragraph",
  list_ordered: "Ordered List",
  list_unordered: "Unordered List",
  table: "Table",
  definition: "Definition",
  how_to: "How-To",
  faq: "FAQ",
  video: "Video",
};

const PROB_COLORS: Record<string, { bg: string; text: string }> = {
  high: { bg: "#d1fae5", text: "#065f46" },
  moderate: { bg: "#fef3c7", text: "#92400e" },
  low: { bg: "#fee2e2", text: "#991b1b" },
};

function formatCurrency(n: number): string {
  if (n >= 1000) return `$${(n / 1000).toFixed(1)}k`;
  return `$${n}`;
}

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, color: C.muted, marginBottom: 12 },
  // Hero strip
  heroBox: { flexDirection: "row", borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 10, marginBottom: 14 },
  heroStat: { flex: 1, alignItems: "center" },
  heroStatValue: { fontSize: 16, fontFamily: "Helvetica-Bold", color: C.ink },
  heroStatLabel: { fontSize: 7, color: C.muted, marginTop: 2, textAlign: "center" },
  heroDivider: { width: 0.75, backgroundColor: C.border },
  // Type breakdown
  sectionLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 8 },
  typeRow: { flexDirection: "row", alignItems: "center", marginBottom: 4, gap: 6 },
  typeLabel: { fontSize: 7, color: C.body, width: 70 },
  typeBarBg: { flex: 1, height: 4, backgroundColor: "#e2e8f0", borderRadius: 2 },
  typeBarFill: { height: 4, backgroundColor: "#3b82f6", borderRadius: 2 },
  typeCount: { fontSize: 7, color: C.muted, width: 12, textAlign: "right" },
  // Reformulation card
  refCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8, marginBottom: 10 },
  refHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 6 },
  refQuery: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink, flex: 1, lineHeight: 1.4 },
  refBadgeRow: { flexDirection: "row", gap: 4, marginBottom: 6 },
  badge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  badgeText: { fontSize: 6.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.3 },
  typeBadge: { backgroundColor: "#dbeafe" },
  typeBadgeText: { color: "#1e40af" },
  // Spec table
  specTable: { marginBottom: 8 },
  specRow: { flexDirection: "row", borderBottomWidth: 0.5, borderBottomColor: C.border, paddingVertical: 3 },
  specLabel: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, width: 80 },
  specValue: { fontSize: 7.5, color: C.body, flex: 1, lineHeight: 1.35 },
  // Schema block
  schemaBox: { backgroundColor: C.surface, borderRadius: 3, padding: 6, marginBottom: 6 },
  schemaType: { fontSize: 8, fontFamily: "Helvetica-Bold", color: "#7c3aed", marginBottom: 2 },
  schemaRationale: { fontSize: 7, color: C.body, lineHeight: 1.35 },
  schemaProps: { flexDirection: "row", flexWrap: "wrap", gap: 3, marginTop: 3 },
  schemaPropPill: { backgroundColor: "#d1fae5", borderRadius: 2, paddingHorizontal: 4, paddingVertical: 1 },
  schemaPropText: { fontSize: 6, color: "#065f46" },
  // Skeleton
  skeletonBox: { borderLeftWidth: 2, borderLeftColor: "#3b82f6", backgroundColor: "#f8fafc", padding: 6, marginBottom: 6 },
  skeletonNote: { fontSize: 6.5, color: C.muted, marginBottom: 3, fontStyle: "italic" },
  skeletonText: { fontSize: 7.5, color: C.body, lineHeight: 1.4, fontStyle: "italic" },
  // Footer
  refFooter: { flexDirection: "row", gap: 12, borderTopWidth: 0.5, borderTopColor: C.border, paddingTop: 5 },
  refFooterStat: { fontSize: 7, color: C.muted },
  refFooterValue: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.ink },
  // Target page
  targetBox: { backgroundColor: C.surface, borderRadius: 3, padding: 5, marginBottom: 6 },
  targetLabel: { fontSize: 7, fontFamily: "Helvetica-Bold", color: "#f59e0b" },
  targetValue: { fontSize: 7, color: C.body },
  // Compact table
  tableHeader: { flexDirection: "row", backgroundColor: C.surface, paddingVertical: 4, paddingHorizontal: 6, marginBottom: 2, borderRadius: 2 },
  tableHeaderCell: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.muted },
  tableRow: { flexDirection: "row", borderBottomWidth: 0.5, borderBottomColor: C.border, paddingVertical: 4, paddingHorizontal: 6 },
  tableCell: { fontSize: 7, color: C.body },
  // Patent footer
  footerBox: { borderTopWidth: 0.5, borderTopColor: C.border, paddingTop: 8, marginTop: 8 },
  footerText: { fontSize: 7, color: C.muted, lineHeight: 1.4 },
});

function ReformulationDetail({ r, index }: { r: CapturedSnippetReformulation; index: number }) {
  const probCfg = PROB_COLORS[r.captureSpec.estimatedCaptureProbability] ?? PROB_COLORS.moderate!;
  const schemaType = r.captureSpec.schemaRequirements[0]?.schemaType ?? "";

  return (
    <View style={s.refCard} wrap={false}>
      <View style={s.refHeader}>
        <Text style={s.refQuery}>{index + 1}. {r.query}</Text>
      </View>

      <View style={s.refBadgeRow}>
        <View style={[s.badge, s.typeBadge]}>
          <Text style={[s.badgeText, s.typeBadgeText]}>{SNIPPET_TYPE_LABELS[r.snippetType]}</Text>
        </View>
        {schemaType.length > 0 && (
          <View style={[s.badge, { backgroundColor: "#ede9fe" }]}>
            <Text style={[s.badgeText, { color: "#4c1d95" }]}>{schemaType}</Text>
          </View>
        )}
        <View style={[s.badge, { backgroundColor: probCfg.bg }]}>
          <Text style={[s.badgeText, { color: probCfg.text }]}>{r.captureSpec.estimatedCaptureProbability.charAt(0).toUpperCase() + r.captureSpec.estimatedCaptureProbability.slice(1)} probability</Text>
        </View>
      </View>

      {/* Target page */}
      <View style={s.targetBox}>
        <Text style={s.targetLabel}>{r.newPageRecommended ? "New page recommended: " : "Existing page: "}</Text>
        <Text style={s.targetValue}>{r.newPageRecommended ? `/${r.newPageSlug}` : (r.targetPageUrl ?? "existing matching page")}</Text>
      </View>

      {/* Spec table */}
      <View style={s.specTable}>
        {[
          { label: "Word count", value: `${r.captureSpec.wordCountTarget.min}-${r.captureSpec.wordCountTarget.max}` },
          { label: "Structure", value: r.captureSpec.paragraphStructure },
          { label: "Header", value: r.captureSpec.headerFormat },
        ].map((row) => (
          <View key={row.label} style={s.specRow}>
            <Text style={s.specLabel}>{row.label}</Text>
            <Text style={s.specValue}>{row.value}</Text>
          </View>
        ))}
      </View>

      {/* Schema requirements */}
      {r.captureSpec.schemaRequirements.length > 0 && (
        <View style={s.schemaBox}>
          {r.captureSpec.schemaRequirements.slice(0, 2).map((req, i) => (
            <View key={i} style={{ marginBottom: i < r.captureSpec.schemaRequirements.length - 1 ? 5 : 0 }}>
              <Text style={s.schemaType}>{req.schemaType}</Text>
              <Text style={s.schemaRationale}>{req.rationale}</Text>
              <View style={s.schemaProps}>
                {req.requiredProperties.slice(0, 6).map((p) => (
                  <View key={p} style={s.schemaPropPill}>
                    <Text style={s.schemaPropText}>{p}</Text>
                  </View>
                ))}
              </View>
            </View>
          ))}
        </View>
      )}

      {/* Content skeleton */}
      <View style={s.skeletonBox} wrap={false}>
        <Text style={s.skeletonNote}>Content skeleton (structural reference, not finished copy):</Text>
        <Text style={s.skeletonText}>{r.captureSpec.contentSkeleton}</Text>
      </View>

      {/* Footer stats */}
      <View style={s.refFooter}>
        <Text style={s.refFooterStat}>Traffic gain: <Text style={s.refFooterValue}>{r.estimatedMonthlyTrafficGain} sessions/mo</Text></Text>
        <Text style={s.refFooterStat}>Revenue gain: <Text style={[s.refFooterValue, { color: "#059669" }]}>{formatCurrency(r.estimatedMonthlyRevenueGain)}/mo</Text></Text>
        {r.captureSpec.captureRationale.length > 0 && (
          <Text style={[s.refFooterStat, { flex: 1 }]}>{r.captureSpec.captureRationale.slice(0, 120)}</Text>
        )}
      </View>
    </View>
  );
}

interface Props {
  snippetCaptureStrategy: SnippetCaptureStrategy;
}

export function SnippetCaptureStrategyPage({ snippetCaptureStrategy }: Props) {
  const {
    totalOpportunitiesAnalyzed,
    totalReformulationsGenerated,
    totalEstimatedMonthlyTrafficGain,
    totalEstimatedMonthlyRevenueGain,
    topPriorityReformulations,
    reformulations,
    snippetTypeBreakdown,
    patentRelevance,
  } = snippetCaptureStrategy;

  const typeEntries = Object.entries(snippetTypeBreakdown) as [SnippetType, number][];
  const maxCount = Math.max(...typeEntries.map(([, v]) => v), 1);

  const remainingReformulations = reformulations.filter(
    (r) => !topPriorityReformulations.some((t) => t.opportunityId === r.opportunityId),
  );

  return (
    <View>
      {/* Page A: Overview */}
      <Text style={s.heading}>Featured Snippet Capture Strategy</Text>
      <Text style={s.subheading}>
        Prescriptive reformulation specs for {totalReformulationsGenerated} non-captured snippet opportunities analyzed from {totalOpportunitiesAnalyzed} total
      </Text>

      {/* Revenue impact hero */}
      <View style={s.heroBox}>
        <View style={s.heroStat}>
          <Text style={[s.heroStatValue, { color: "#059669" }]}>{formatCurrency(totalEstimatedMonthlyRevenueGain)}</Text>
          <Text style={s.heroStatLabel}>Est. monthly revenue gain</Text>
        </View>
        <View style={s.heroDivider} />
        <View style={s.heroStat}>
          <Text style={[s.heroStatValue, { color: "#3b82f6" }]}>{totalEstimatedMonthlyTrafficGain.toLocaleString()}</Text>
          <Text style={s.heroStatLabel}>Est. monthly sessions</Text>
        </View>
        <View style={s.heroDivider} />
        <View style={s.heroStat}>
          <Text style={s.heroStatValue}>{totalReformulationsGenerated}</Text>
          <Text style={s.heroStatLabel}>Reformulations generated</Text>
        </View>
      </View>

      {/* Type breakdown */}
      {typeEntries.length > 0 && (
        <>
          <Text style={s.sectionLabel}>Snippet Type Breakdown</Text>
          {typeEntries.sort(([, a], [, b]) => b - a).map(([type, count]) => (
            <View key={type} style={s.typeRow}>
              <Text style={s.typeLabel}>{SNIPPET_TYPE_LABELS[type]}</Text>
              <View style={s.typeBarBg}>
                <View style={[s.typeBarFill, { width: `${Math.round((count / maxCount) * 100)}%` }]} />
              </View>
              <Text style={s.typeCount}>{count}</Text>
            </View>
          ))}
        </>
      )}

      <View style={s.footerBox}>
        <Text style={s.footerText}>{patentRelevance}</Text>
      </View>

      {/* Pages B-F: Priority reformulations */}
      {topPriorityReformulations.map((r, i) => (
        <View key={r.opportunityId} break>
          <Text style={s.sectionLabel}>Priority Reformulation {i + 1} of {topPriorityReformulations.length}</Text>
          <ReformulationDetail r={r} index={i} />
        </View>
      ))}

      {/* Page G: Compact remaining reformulations table */}
      {remainingReformulations.length > 0 && (
        <View break>
          <Text style={s.heading}>Additional Reformulations</Text>
          <Text style={s.subheading}>{remainingReformulations.length} additional capture opportunities</Text>

          <View style={s.tableHeader}>
            <Text style={[s.tableHeaderCell, { flex: 3 }]}>Query</Text>
            <Text style={[s.tableHeaderCell, { width: 60 }]}>Type</Text>
            <Text style={[s.tableHeaderCell, { width: 55 }]}>Probability</Text>
            <Text style={[s.tableHeaderCell, { width: 55 }]}>Rev Gain/Mo</Text>
          </View>

          {remainingReformulations.map((r) => {
            const probCfg = PROB_COLORS[r.captureSpec.estimatedCaptureProbability] ?? PROB_COLORS.moderate!;
            return (
              <View key={r.opportunityId} style={s.tableRow}>
                <Text style={[s.tableCell, { flex: 3, lineHeight: 1.3 }]}>{r.query.slice(0, 70)}</Text>
                <Text style={[s.tableCell, { width: 60 }]}>{SNIPPET_TYPE_LABELS[r.snippetType]}</Text>
                <Text style={[s.tableCell, { width: 55, color: probCfg.text }]}>
                  {r.captureSpec.estimatedCaptureProbability.charAt(0).toUpperCase() + r.captureSpec.estimatedCaptureProbability.slice(1)}
                </Text>
                <Text style={[s.tableCell, { width: 55, color: "#059669", fontFamily: "Helvetica-Bold" }]}>
                  {formatCurrency(r.estimatedMonthlyRevenueGain)}
                </Text>
              </View>
            );
          })}
        </View>
      )}
    </View>
  );
}
