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

interface OpportunityContext {
  totalMonthlyUsd: number;
  confidence: "high" | "moderate" | "low";
}

const s = StyleSheet.create({
  // ── Page 1: Headline ──
  headlineRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 },
  scoreBox: {},
  scoreNum: { fontSize: 52, fontFamily: "Helvetica-Bold", color: C.ink, lineHeight: 1 },
  scoreLabel: { fontSize: 9, color: C.muted, marginTop: 3 },
  industryBadge: { backgroundColor: C.accentLight, borderRadius: 4, paddingHorizontal: 8, paddingVertical: 3 },
  industryBadgeText: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.accentDark },
  metricBox: { backgroundColor: C.surface, borderRadius: 4, padding: 10, marginBottom: 12, borderWidth: 0.75, borderColor: C.border },
  metricLabel: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 3 },
  metricText: { fontSize: 11, fontFamily: "Helvetica-Bold", color: C.ink },
  narrativeText: { fontSize: 9.5, color: C.body, lineHeight: 1.6, marginBottom: 16 },
  sectionLabel: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 1, textTransform: "uppercase", marginBottom: 8 },
  // themes
  themeCard: { borderWidth: 0.75, borderColor: C.border, borderLeftWidth: 3, borderLeftColor: C.accent, borderRadius: 3, padding: 8, marginBottom: 6, backgroundColor: C.surface },
  themeTitle: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 2 },
  themeDesc: { fontSize: 8.5, color: C.body, lineHeight: 1.5 },
  areaRow: { flexDirection: "row", flexWrap: "wrap", gap: 4, marginTop: 4 },
  areaPill: { backgroundColor: "#f1f5f9", borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  areaPillText: { fontSize: 7, color: C.muted },
  // ── Page 2: Critical Finding + Top 5 ──
  criticalBox: { backgroundColor: "#fef2f2", borderRadius: 4, padding: 10, marginBottom: 12, borderWidth: 0.75, borderColor: "#fecaca" },
  criticalLabel: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: "#dc2626", letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 4 },
  criticalTitle: { fontSize: 11, fontFamily: "Helvetica-Bold", color: "#7f1d1d", marginBottom: 6 },
  criticalFraming: { fontSize: 9, color: "#991b1b", lineHeight: 1.55, marginBottom: 8 },
  criticalMetaRow: { flexDirection: "row", gap: 8 },
  criticalMetaCard: { flex: 1, backgroundColor: "#ffffff", borderRadius: 3, padding: 7, borderWidth: 0.5, borderColor: "#fecaca" },
  criticalMetaLabel: { fontSize: 7, fontFamily: "Helvetica-Bold", color: "#dc2626", letterSpacing: 0.7, marginBottom: 2 },
  criticalMetaText: { fontSize: 8, color: "#7f1d1d", lineHeight: 1.4 },
  findingRow: { flexDirection: "row", alignItems: "flex-start", marginBottom: 7, gap: 8 },
  findingRank: { width: 20, height: 20, borderRadius: 10, backgroundColor: C.surface, borderWidth: 0.75, borderColor: C.border, alignItems: "center", justifyContent: "center" },
  findingRankText: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted },
  findingContent: { flex: 1 },
  findingHeader: { flexDirection: "row", alignItems: "center", gap: 6, marginBottom: 3 },
  severityPill: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  severityPillText: { fontSize: 7, fontFamily: "Helvetica-Bold" },
  findingSectionTag: { fontSize: 7, color: C.caption },
  findingTitle: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 2 },
  findingImpact: { fontSize: 8.5, color: C.body, lineHeight: 1.4, marginBottom: 3 },
  findingOpportunity: { backgroundColor: C.accentLight, borderRadius: 3, paddingHorizontal: 5, paddingVertical: 2, alignSelf: "flex-start", marginBottom: 3 },
  findingOpportunityText: { fontSize: 7.5, color: C.accentDark, fontFamily: "Helvetica-Bold" },
  findingRec: { fontSize: 8, color: C.muted, lineHeight: 1.4 },
  // ── Page 3: Quick Wins ──
  winCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 10, marginBottom: 8 },
  winRankRow: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", marginBottom: 6 },
  winRankCircle: { width: 20, height: 20, borderRadius: 10, backgroundColor: "#f0fdf4", alignItems: "center", justifyContent: "center", borderWidth: 0.75, borderColor: "#bbf7d0" },
  winRankText: { fontSize: 8, fontFamily: "Helvetica-Bold", color: "#166534" },
  winEffort: { fontSize: 8, color: C.muted },
  winTitle: { fontSize: 10, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 4 },
  winLiftBadge: { backgroundColor: "#f0fdf4", borderRadius: 3, paddingHorizontal: 6, paddingVertical: 2, alignSelf: "flex-start", marginBottom: 5 },
  winLiftText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: "#166534" },
  winNote: { fontSize: 8.5, color: C.body, lineHeight: 1.5, marginBottom: 4 },
  winWhy: { fontSize: 8, color: C.accentDark, lineHeight: 1.4 },
  // ── Page 4: 90-Day Outlook ──
  outlookBarBg: { height: 10, backgroundColor: C.surface, borderRadius: 5, overflow: "hidden", marginBottom: 4, borderWidth: 0.5, borderColor: C.border },
  outlookBarFill: { height: 10, borderRadius: 5 },
  outlookLabels: { flexDirection: "row", justifyContent: "space-between", marginBottom: 10 },
  outlookLabelText: { fontSize: 8, color: C.muted },
  outlookScores: { flexDirection: "row", justifyContent: "space-between", marginBottom: 14 },
  outlookScoreText: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink },
  phaseRow: { flexDirection: "row", alignItems: "flex-start", gap: 8, marginBottom: 6, padding: 7, borderWidth: 0.75, borderColor: C.border, borderRadius: 3 },
  phaseTag: { backgroundColor: C.surface, borderRadius: 2, paddingHorizontal: 5, paddingVertical: 2 },
  phaseTagText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted },
  phaseFocus: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 1 },
  phaseMilestone: { fontSize: 8, color: C.muted, lineHeight: 1.4 },
  confidenceNote: { fontSize: 8, color: C.caption, fontFamily: "Helvetica-Oblique", marginTop: 8 },
  outlookMeta: { flexDirection: "row", justifyContent: "space-between", marginBottom: 8 },
  outlookMetaText: { fontSize: 8, color: C.muted },
  // ── Opportunity strip (Page 4) ──
  opportunityStrip: { flexDirection: "row", alignItems: "center", backgroundColor: "#ecfdf5", borderRadius: 4, paddingHorizontal: 10, paddingVertical: 7, marginBottom: 12, borderWidth: 0.75, borderColor: "#6ee7b7" },
  opportunityStripLabel: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: "#065f46", flex: 1 },
  opportunityStripValue: { fontSize: 11, fontFamily: "Helvetica-Bold", color: "#065f46" },
  opportunityStripDisclaimer: { fontSize: 6.5, color: "#047857", marginTop: 2 },
  // ── Page 5: Closing ──
  closingNarrative: { fontSize: 9.5, color: C.body, lineHeight: 1.6, marginBottom: 12 },
  insightCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 9, marginBottom: 7 },
  insightTitle: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 3 },
  insightStat: { fontSize: 8.5, color: C.accentDark, fontFamily: "Helvetica-Bold", marginBottom: 3 },
  insightAction: { fontSize: 8, color: C.muted },
  patentNote: { fontSize: 8, color: C.caption, fontFamily: "Helvetica-Oblique", marginTop: 8 },
  previewCard: { borderWidth: 0.75, borderColor: "#e0e7ff", borderRadius: 4, padding: 9, marginBottom: 7, backgroundColor: "#fafbff" },
  previewRow: { flexDirection: "row", gap: 10, marginBottom: 7 },
  previewCol: { flex: 1 },
  previewColLabel: { fontSize: 7, fontFamily: "Helvetica-Bold", letterSpacing: 0.7, textTransform: "uppercase", marginBottom: 2 },
  previewColText: { fontSize: 8.5, color: C.body, lineHeight: 1.4 },
  previewDivider: { borderTopWidth: 0.5, borderTopColor: C.border, paddingTop: 5 },
  previewBizText: { fontSize: 8, color: C.muted, lineHeight: 1.4 },
  ctaBox: { backgroundColor: C.accentDark, borderRadius: 4, padding: 12, alignItems: "center", marginTop: 12 },
  ctaText: { fontSize: 10, fontFamily: "Helvetica-Bold", color: C.white, textAlign: "center" },
});

const SEVERITY_STYLES: Record<string, { bg: string; text: string }> = {
  critical: { bg: "#fef2f2", text: "#dc2626" },
  high: { bg: "#fffbeb", text: "#d97706" },
  moderate: { bg: "#fefce8", text: "#ca8a04" },
};

interface Props {
  brief: ExecutiveBrief;
  isFirstParty: boolean;
  opportunityContext?: OpportunityContext | null;
}

export function ExecutiveBriefPdfSection({ brief, isFirstParty, opportunityContext }: Props) {
  const { headline, crossCuttingThemes, criticalFinding, topFindings, topQuickWins, ninetyDayOutlook, closingPage } = brief;
  const maxScore = ninetyDayOutlook.maxPossibleScore;
  const pct = (v: number) => Math.min(100, Math.round((v / maxScore) * 100));

  return (
    <View>
      {/* ── PAGE 1: Headline + Themes ── */}
      <View>
        <Text style={[S.label, { marginBottom: 10 }]}>Executive Brief</Text>

        <View style={s.headlineRow} wrap={false}>
          <View style={s.scoreBox}>
            <Text style={s.scoreNum}>{headline.auditScore}</Text>
            <Text style={s.scoreLabel}>{headline.scoreLabel}</Text>
          </View>
          <View style={s.industryBadge}>
            <Text style={s.industryBadgeText}>{headline.industryPosition}</Text>
          </View>
        </View>

        <View style={s.metricBox} wrap={false}>
          <Text style={s.metricLabel}>Standout Metric</Text>
          <Text style={s.metricText}>{headline.keyMetric}</Text>
        </View>

        <Text style={s.narrativeText}>{headline.narrative}</Text>

        {crossCuttingThemes.length > 0 && (
          <View>
            <Text style={s.sectionLabel}>Cross-Cutting Themes</Text>
            {crossCuttingThemes.map((theme, i) => (
              <View key={i} style={s.themeCard} wrap={false}>
                <Text style={s.themeTitle}>{theme.title}</Text>
                <Text style={s.themeDesc}>{theme.description}</Text>
                {theme.affectedAreas.length > 0 && (
                  <View style={s.areaRow}>
                    {theme.affectedAreas.map((area) => (
                      <View key={area} style={s.areaPill}>
                        <Text style={s.areaPillText}>{area}</Text>
                      </View>
                    ))}
                  </View>
                )}
              </View>
            ))}
          </View>
        )}
      </View>

      {/* ── PAGE 2: Critical Finding + Top 5 Findings ── */}
      <View break>
        <Text style={[S.label, { marginBottom: 10 }]}>Critical Finding + Top 5</Text>

        <View style={s.criticalBox} wrap={false}>
          <Text style={s.criticalLabel}>The Critical Finding</Text>
          <Text style={s.criticalTitle}>{criticalFinding.title}</Text>
          <Text style={s.criticalFraming}>{criticalFinding.framing}</Text>
          <View style={s.criticalMetaRow}>
            <View style={s.criticalMetaCard}>
              <Text style={s.criticalMetaLabel}>Business Impact</Text>
              <Text style={s.criticalMetaText}>{criticalFinding.affectedBusinessOutcome}</Text>
            </View>
            <View style={s.criticalMetaCard}>
              <Text style={s.criticalMetaLabel}>Primary Remediation</Text>
              <Text style={s.criticalMetaText}>{criticalFinding.primaryRemediation}</Text>
            </View>
          </View>
        </View>

        <Text style={[s.sectionLabel, { marginTop: 10 }]}>Top 5 Findings</Text>
        {topFindings.map((finding) => {
          const sevStyle = SEVERITY_STYLES[finding.severity] ?? SEVERITY_STYLES.moderate;
          return (
            <View key={finding.rank} style={s.findingRow} wrap={false}>
              <View style={s.findingRank}>
                <Text style={s.findingRankText}>{finding.rank}</Text>
              </View>
              <View style={s.findingContent}>
                <View style={s.findingHeader}>
                  <View style={[s.severityPill, { backgroundColor: sevStyle.bg }]}>
                    <Text style={[s.severityPillText, { color: sevStyle.text }]}>{finding.severity}</Text>
                  </View>
                  <Text style={s.findingSectionTag}>{finding.affectedSection}</Text>
                </View>
                <Text style={s.findingTitle}>{finding.title}</Text>
                <Text style={s.findingImpact}>{finding.impactSummary}</Text>
                {finding.quantifiedOpportunity && (
                  <View style={s.findingOpportunity}>
                    <Text style={s.findingOpportunityText}>{finding.quantifiedOpportunity}</Text>
                  </View>
                )}
                <Text style={s.findingRec}>{finding.primaryRecommendation}</Text>
              </View>
            </View>
          );
        })}
      </View>

      {/* ── PAGE 3: Top Quick Wins ── */}
      <View break>
        <Text style={[S.label, { marginBottom: 4 }]}>Implementation Order: Top 3 Quick Wins</Text>
        <Text style={[s.narrativeText, { marginBottom: 12 }]}>
          Ranked by effort-to-impact ratio. Complete in sequence for the fastest path to visible score improvement.
        </Text>
        {topQuickWins.map((win) => (
          <View key={win.rank} style={s.winCard} wrap={false}>
            <View style={s.winRankRow}>
              <View style={s.winRankCircle}>
                <Text style={s.winRankText}>{win.rank}</Text>
              </View>
              <Text style={s.winEffort}>{win.effortHours}h effort</Text>
            </View>
            <Text style={s.winTitle}>{win.title}</Text>
            <View style={s.winLiftBadge}>
              <Text style={s.winLiftText}>{win.expectedLift}</Text>
            </View>
            <Text style={s.winNote}>{win.implementationNote}</Text>
            <Text style={s.winWhy}>{win.whyFirst}</Text>
          </View>
        ))}
        <Text style={[s.narrativeText, { marginTop: 8, color: C.muted, fontSize: 8.5 }]}>
          These three actions in sequence are the fastest path to visible audit score improvement.
        </Text>
      </View>

      {/* ── PAGE 4: 90-Day Strategic Outlook ── */}
      <View break>
        <Text style={[S.label, { marginBottom: 10 }]}>90-Day Strategic Outlook</Text>

        {/* Score progression bar */}
        <View wrap={false}>
          <View style={s.outlookLabels}>
            <Text style={s.outlookLabelText}>Current</Text>
            <Text style={s.outlookLabelText}>30d</Text>
            <Text style={s.outlookLabelText}>60d</Text>
            <Text style={s.outlookLabelText}>90d</Text>
          </View>
          <View style={s.outlookBarBg}>
            <View style={[s.outlookBarFill, { width: `${pct(ninetyDayOutlook.projectedScore90d)}%`, backgroundColor: "#bfdbfe" }]} />
          </View>
          <View style={s.outlookBarBg}>
            <View style={[s.outlookBarFill, { width: `${pct(ninetyDayOutlook.projectedScore60d)}%`, backgroundColor: "#93c5fd" }]} />
          </View>
          <View style={s.outlookBarBg}>
            <View style={[s.outlookBarFill, { width: `${pct(ninetyDayOutlook.projectedScore30d)}%`, backgroundColor: "#60a5fa" }]} />
          </View>
          <View style={s.outlookBarBg}>
            <View style={[s.outlookBarFill, { width: `${pct(ninetyDayOutlook.currentScore)}%`, backgroundColor: C.muted }]} />
          </View>
          <View style={s.outlookScores}>
            <Text style={s.outlookScoreText}>{ninetyDayOutlook.currentScore}</Text>
            <Text style={[s.outlookScoreText, { color: "#2563eb" }]}>{ninetyDayOutlook.projectedScore30d}</Text>
            <Text style={[s.outlookScoreText, { color: "#2563eb" }]}>{ninetyDayOutlook.projectedScore60d}</Text>
            <Text style={[s.outlookScoreText, { color: "#2563eb" }]}>{ninetyDayOutlook.projectedScore90d}</Text>
          </View>
          <View style={s.outlookMeta}>
            <Text style={s.outlookMetaText}>Max possible: {maxScore}</Text>
            <Text style={s.outlookMetaText}>Total effort: ~{ninetyDayOutlook.totalEffortHours}h</Text>
          </View>
        </View>

        <Text style={[s.sectionLabel, { marginTop: 4 }]}>Phase Highlights</Text>
        {ninetyDayOutlook.phaseHighlights.map((phase, i) => (
          <View key={i} style={s.phaseRow} wrap={false}>
            <View style={s.phaseTag}>
              <Text style={s.phaseTagText}>{phase.phaseName}</Text>
            </View>
            <View style={{ flex: 1 }}>
              <Text style={s.phaseFocus}>{phase.primaryFocus}</Text>
              <Text style={s.phaseMilestone}>{phase.keyMilestone}</Text>
            </View>
          </View>
        ))}
        <Text style={s.confidenceNote}>{ninetyDayOutlook.confidenceNote}</Text>

        {/* Opportunity cost strip — only when confidence is moderate or high */}
        {opportunityContext && opportunityContext.confidence !== "low" && (
          <View style={s.opportunityStrip} wrap={false}>
            <View style={{ flex: 1 }}>
              <Text style={s.opportunityStripLabel}>Estimated Opportunity Cost from Current Structural Gaps</Text>
              <Text style={s.opportunityStripDisclaimer}>Directional estimate based on industry benchmarks — not a measurement</Text>
            </View>
            <Text style={s.opportunityStripValue}>
              ~${opportunityContext.totalMonthlyUsd.toLocaleString()}/mo
            </Text>
          </View>
        )}
      </View>

      {/* ── PAGE 5: Closing (audit-type-specific) ── */}
      <View break>
        {closingPage.type === "behavioral_highlights" && closingPage.behavioralHighlights && (
          <View>
            <Text style={[S.label, { marginBottom: 8 }]}>Behavioral Intelligence Highlights</Text>
            <Text style={s.closingNarrative}>{closingPage.behavioralHighlights.narrative}</Text>
            {closingPage.behavioralHighlights.topInsights.map((insight, i) => (
              <View key={i} style={s.insightCard} wrap={false}>
                <Text style={s.insightTitle}>{insight.insight}</Text>
                <Text style={s.insightStat}>{insight.supportingData}</Text>
                <Text style={s.insightAction}>Connected action: {insight.connectedAction}</Text>
              </View>
            ))}
            <Text style={s.patentNote}>{closingPage.behavioralHighlights.patentRelevance}</Text>
          </View>
        )}

        {closingPage.type === "first_party_preview" && closingPage.firstPartyPreview && (
          <View>
            <Text style={[S.label, { marginBottom: 8 }]}>What First-Party Data Would Reveal</Text>
            <Text style={s.closingNarrative}>{closingPage.firstPartyPreview.narrative}</Text>
            {closingPage.firstPartyPreview.previewCallouts.map((callout, i) => (
              <View key={i} style={s.previewCard} wrap={false}>
                <View style={s.previewRow}>
                  <View style={s.previewCol}>
                    <Text style={[s.previewColLabel, { color: C.muted }]}>Current Estimate</Text>
                    <Text style={s.previewColText}>{callout.currentEstimate}</Text>
                  </View>
                  <View style={s.previewCol}>
                    <Text style={[s.previewColLabel, { color: C.accentDark }]}>With Site Tag</Text>
                    <Text style={[s.previewColText, { fontFamily: "Helvetica-Bold", color: C.accentDark }]}>{callout.firstPartyReveal}</Text>
                  </View>
                </View>
                <View style={s.previewDivider}>
                  <Text style={s.previewBizText}>{callout.businessRelevance}</Text>
                </View>
              </View>
            ))}
            <View style={s.ctaBox} wrap={false}>
              <Text style={s.ctaText}>{closingPage.firstPartyPreview.ctaText}</Text>
            </View>
          </View>
        )}
      </View>
    </View>
  );
}
