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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, marginBottom: 16, color: C.muted },
  // Confidence badge
  badge: { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2, alignSelf: "flex-start", marginBottom: 14 },
  badgeText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.8 },
  // Headline block
  headlineBlock: { borderRadius: 6, padding: 16, marginBottom: 16, alignItems: "center" },
  headlineValue: { fontSize: 30, fontFamily: "Helvetica-Bold", color: "#065f46", marginBottom: 2 },
  headlineAnnual: { fontSize: 11, color: "#047857", marginBottom: 4 },
  headlineNote: { fontSize: 7, color: C.muted, textAlign: "center" },
  // Top 3 cards
  topRow: { flexDirection: "row", gap: 8, marginBottom: 14 },
  topCard: { flex: 1, borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8 },
  topRank: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.muted, marginBottom: 3 },
  topAmount: { fontSize: 14, fontFamily: "Helvetica-Bold", color: "#065f46", marginBottom: 2 },
  topTitle: { fontSize: 7, color: C.body, lineHeight: 1.4, marginBottom: 2 },
  topEffort: { fontSize: 6.5, color: C.muted },
  // Baselines strip
  baselineRow: { flexDirection: "row", gap: 12, backgroundColor: C.surface, borderRadius: 4, padding: 8, marginBottom: 14 },
  baselineItem: { flex: 1 },
  baselineLabel: { fontSize: 6.5, color: C.muted, marginBottom: 1 },
  baselineValue: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink },
  // Per-finding table
  section: { marginBottom: 12 },
  sectionHeading: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 6 },
  table: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, overflow: "hidden" },
  headerRow: { flexDirection: "row", backgroundColor: C.surface, paddingHorizontal: 6, paddingVertical: 4, borderBottomWidth: 0.75, borderBottomColor: C.border },
  tableRow: { flexDirection: "row", paddingHorizontal: 6, paddingVertical: 3.5, borderBottomWidth: 0.5, borderBottomColor: "#f1f5f9" },
  rowAlt: { backgroundColor: "#fafafa" },
  colHeader: { fontSize: 6.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.5 },
  cellText: { fontSize: 7.5, color: C.body },
  cellBold: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: "#065f46" },
  cellMuted: { fontSize: 6.5, color: C.muted },
  confidenceBadge: { borderRadius: 2, paddingHorizontal: 4, paddingVertical: 1.5 },
  // Disclosures
  disclosureBox: { borderWidth: 0.75, borderColor: "#fde68a", borderRadius: 4, padding: 8, backgroundColor: "#fffbeb", marginTop: 8 },
  disclosureTitle: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: "#92400e", marginBottom: 4 },
  disclosureText: { fontSize: 7, color: "#b45309", lineHeight: 1.45, marginBottom: 3 },
  disclosureFactor: { fontSize: 6.5, color: "#b45309", marginBottom: 2 },
});

function confidenceBg(c: "high" | "moderate" | "low"): string {
  return c === "high" ? "#d1fae5" : c === "moderate" ? "#fef3c7" : "#f1f5f9";
}
function confidenceFg(c: "high" | "moderate" | "low"): string {
  return c === "high" ? "#065f46" : c === "moderate" ? "#92400e" : "#64748b";
}

function fmtUsd(n: number): string {
  if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `$${Math.round(n / 1000)}k`;
  return `$${n.toLocaleString()}`;
}

export function LostOpportunityCalculatorPage({
  lostOpportunityCalculation,
}: {
  lostOpportunityCalculation: LostOpportunityCalculation;
}) {
  const loc = lostOpportunityCalculation;
  const agg = loc.aggregateOpportunity;
  const baselines = loc.industryBaselines;

  return (
    <View>
      <Text style={s.heading}>Estimated Monthly Opportunity Cost</Text>
      <Text style={s.subheading}>Directional revenue impact estimates based on industry benchmarks — not measurements</Text>

      {/* Confidence badge */}
      <View style={[s.badge, { backgroundColor: confidenceBg(loc.confidence) }]}>
        <Text style={[s.badgeText, { color: confidenceFg(loc.confidence) }]}>
          {loc.confidence.toUpperCase()} CONFIDENCE
        </Text>
      </View>

      {/* Headline block */}
      <View style={[s.headlineBlock, { backgroundColor: "#ecfdf5" }]} wrap={false}>
        <Text style={s.headlineValue}>~{fmtUsd(agg.totalMonthlyOpportunityUsd)} / month</Text>
        <Text style={s.headlineAnnual}>~{fmtUsd(agg.annualizedOpportunityUsd)} annualized</Text>
        <Text style={s.headlineNote}>
          Estimated based on {baselines.industryVertical} industry conversion rate ({(baselines.avgConversionRate * 100).toFixed(1)}%) and avg customer value (${baselines.avgCustomerValue.toLocaleString()})
        </Text>
      </View>

      {/* Top 3 cards */}
      {agg.topThreeMonthlyImpact.length > 0 && (
        <View style={s.topRow} wrap={false}>
          {agg.topThreeMonthlyImpact.map((item, i) => (
            <View key={i} style={s.topCard}>
              <Text style={s.topRank}>#{i + 1} HIGHEST IMPACT</Text>
              <Text style={s.topAmount}>{fmtUsd(item.monthlyImpactUsd)}/mo</Text>
              <Text style={s.topTitle}>{item.findingTitle}</Text>
              <Text style={s.topEffort}>Est. effort: {item.timeToImplement}</Text>
            </View>
          ))}
        </View>
      )}

      {/* Industry baselines */}
      <View style={s.baselineRow} wrap={false}>
        <View style={s.baselineItem}>
          <Text style={s.baselineLabel}>Industry</Text>
          <Text style={s.baselineValue}>{baselines.industryVertical}</Text>
        </View>
        <View style={s.baselineItem}>
          <Text style={s.baselineLabel}>Avg CVR</Text>
          <Text style={s.baselineValue}>{(baselines.avgConversionRate * 100).toFixed(1)}%</Text>
        </View>
        <View style={s.baselineItem}>
          <Text style={s.baselineLabel}>Avg customer value</Text>
          <Text style={s.baselineValue}>${baselines.avgCustomerValue.toLocaleString()}</Text>
        </View>
        <View style={[s.baselineItem, { flex: 2 }]}>
          <Text style={s.baselineLabel}>Benchmark source</Text>
          <Text style={[s.baselineValue, { fontSize: 6.5, fontFamily: "Helvetica" }]}>{baselines.sourceNote}</Text>
        </View>
      </View>

      {/* Per-finding table */}
      <View style={s.section}>
        <Text style={s.sectionHeading}>Per-Finding Estimates</Text>
        <View style={s.table}>
          <View style={s.headerRow}>
            <Text style={[s.colHeader, { flex: 2.5 }]}>FINDING</Text>
            <Text style={[s.colHeader, { flex: 1.2 }]}>SECTION</Text>
            <Text style={[s.colHeader, { flex: 0.9, textAlign: "right" }]}>VOLUME/MO</Text>
            <Text style={[s.colHeader, { flex: 0.7, textAlign: "right" }]}>RECOV%</Text>
            <Text style={[s.colHeader, { flex: 0.9, textAlign: "right" }]}>SESSIONS</Text>
            <Text style={[s.colHeader, { flex: 0.8, textAlign: "right" }]}>CONVS</Text>
            <Text style={[s.colHeader, { flex: 0.9, textAlign: "right" }]}>REV/MO</Text>
            <Text style={[s.colHeader, { flex: 0.8 }]}>CONF</Text>
          </View>
          {loc.perFindingEstimates.map((e, i) => (
            <View key={i} style={[s.tableRow, i % 2 === 1 ? s.rowAlt : {}]} wrap={false}>
              <Text style={[s.cellText, { flex: 2.5 }]}>{e.findingTitle.slice(0, 60)}{e.findingTitle.length > 60 ? "…" : ""}</Text>
              <Text style={[s.cellMuted, { flex: 1.2 }]}>{e.findingSection}</Text>
              <Text style={[s.cellText, { flex: 0.9, textAlign: "right" }]}>{e.affectedQueryVolumeMonthly.toLocaleString()}</Text>
              <Text style={[s.cellText, { flex: 0.7, textAlign: "right" }]}>{e.estimatedRecoverableTrafficPercent}%</Text>
              <Text style={[s.cellText, { flex: 0.9, textAlign: "right" }]}>{e.estimatedRecoverableSessionsMonthly.toLocaleString()}</Text>
              <Text style={[s.cellText, { flex: 0.8, textAlign: "right" }]}>{e.estimatedConversionsMonthly.toFixed(1)}</Text>
              <Text style={[s.cellBold, { flex: 0.9, textAlign: "right" }]}>{fmtUsd(e.estimatedRevenueMonthly)}</Text>
              <View style={[s.confidenceBadge, { flex: 0.8, backgroundColor: confidenceBg(e.confidenceLevel) }]}>
                <Text style={{ fontSize: 6, color: confidenceFg(e.confidenceLevel), fontFamily: "Helvetica-Bold" }}>
                  {e.confidenceLevel}
                </Text>
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* Disclosures */}
      <View style={s.disclosureBox} wrap={false}>
        <Text style={s.disclosureTitle}>Estimation Disclosures</Text>
        <Text style={s.disclosureText}>{loc.disclosures.estimationDisclosure}</Text>
        <Text style={s.disclosureText}>{loc.disclosures.assumptionsNote}</Text>
        {loc.disclosures.confidenceFactors.map((f, i) => (
          <Text key={i} style={s.disclosureFactor}>• {f}</Text>
        ))}
      </View>
    </View>
  );
}
