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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, marginBottom: 14, color: C.muted },
  // Top categories
  categoriesBox: { backgroundColor: "#f5f3ff", borderWidth: 0.75, borderColor: "#ddd6fe", borderRadius: 4, padding: 10, marginBottom: 14 },
  categoriesTitle: { fontSize: 8, fontFamily: "Helvetica-Bold", color: "#5b21b6", marginBottom: 6 },
  categoriesGrid: { flexDirection: "row", flexWrap: "wrap", gap: 6 },
  categoryItem: { flex: 1, minWidth: "40%" },
  categoryCount: { fontSize: 8, fontFamily: "Helvetica-Bold", color: "#5b21b6" },
  categoryLabel: { fontSize: 7.5, color: C.ink, marginBottom: 1 },
  categorySummary: { fontSize: 6.5, color: C.muted, lineHeight: 1.35 },
  // Competitor section
  competitorSection: { marginBottom: 16 },
  competitorHeading: { fontSize: 9.5, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 2 },
  competitorUrl: { fontSize: 6.5, color: C.muted, marginBottom: 6 },
  narrative: { fontSize: 7.5, color: C.body, lineHeight: 1.5, marginBottom: 10 },
  // Screenshot
  screenshotLabel: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.muted, marginBottom: 4 },
  sideBySide: { width: "100%", borderRadius: 4, marginBottom: 10, objectFit: "cover", maxHeight: 280 },
  // Differences table
  table: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, overflow: "hidden", marginBottom: 8 },
  headerRow: { flexDirection: "row", backgroundColor: C.surface, paddingHorizontal: 6, paddingVertical: 3, borderBottomWidth: 0.75, borderBottomColor: C.border },
  tableRow: { flexDirection: "row", paddingHorizontal: 6, paddingVertical: 3, borderBottomWidth: 0.5, borderBottomColor: "#f1f5f9" },
  rowAlt: { backgroundColor: "#fafafa" },
  colHeader: { fontSize: 6, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.5 },
  cellText: { fontSize: 7, color: C.body },
  cellMuted: { fontSize: 6.5, color: C.muted },
  badge: { borderRadius: 2, paddingHorizontal: 4, paddingVertical: 1 },
  disclosureText: { fontSize: 7, color: C.muted, fontStyle: "italic", marginTop: 8 },
});

const IMPACT_COLORS: Record<VisualComparisonDifference["impact"], { bg: string; fg: string }> = {
  critical: { bg: "#fee2e2", fg: "#dc2626" },
  high:     { bg: "#ffedd5", fg: "#ea580c" },
  moderate: { bg: "#fef3c7", fg: "#d97706" },
  low:      { bg: "#f1f5f9", fg: "#6b7280" },
};

const CATEGORY_LABEL: Record<VisualComparisonDifference["category"], string> = {
  cta: "CTA",
  social_proof: "Social Proof",
  trust_signals: "Trust Signals",
  content_depth: "Content Depth",
  navigation: "Navigation",
  visual_design: "Visual Design",
};

export function CompetitorVisualComparisonPage({
  competitorVisualComparison,
}: {
  competitorVisualComparison: CompetitorVisualComparison;
}) {
  const cvc = competitorVisualComparison;
  const totalDiffs = cvc.comparisons.reduce((s, c) => s + c.homepageComparison.differences.length, 0);

  return (
    <View>
      <Text style={s.heading}>Side-by-Side Competitor Visual Comparison</Text>
      <Text style={s.subheading}>
        {cvc.comparisons.length} competitor{cvc.comparisons.length !== 1 ? "s" : ""} compared · {totalDiffs} structural differences · {new Date(cvc.windowDate).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
      </Text>

      {/* Top difference categories */}
      {cvc.topDifferenceCategories.length > 0 && (
        <View style={s.categoriesBox} wrap={false}>
          <Text style={s.categoriesTitle}>Most Common Gaps Across Competitors</Text>
          <View style={s.categoriesGrid}>
            {cvc.topDifferenceCategories.slice(0, 4).map((cat, i) => (
              <View key={i} style={s.categoryItem}>
                <Text style={s.categoryCount}>{cat.occurrenceCount}×</Text>
                <Text style={s.categoryLabel}>{cat.category}</Text>
                <Text style={s.categorySummary}>{cat.summary.slice(0, 80)}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Per-competitor sections */}
      {cvc.comparisons.map((comp, ci) => (
        <View key={ci} style={s.competitorSection} break={ci > 0}>
          <Text style={s.competitorHeading}>vs {comp.competitorName}</Text>
          <Text style={s.competitorUrl}>{comp.competitorUrl}</Text>
          <Text style={s.narrative}>{comp.summaryNarrative}</Text>

          {/* Side-by-side image */}
          {comp.homepageComparison.sideBySideUrl ? (
            <>
              <Text style={s.screenshotLabel}>Homepage Side-by-Side Comparison</Text>
              <Image src={comp.homepageComparison.sideBySideUrl} style={s.sideBySide} />
            </>
          ) : comp.homepageComparison.brandScreenshotUrl && comp.homepageComparison.competitorScreenshotUrl ? (
            <View style={{ flexDirection: "row", gap: 6, marginBottom: 10 }}>
              <View style={{ flex: 1 }}>
                <Text style={s.screenshotLabel}>Your Site</Text>
                <Image src={comp.homepageComparison.brandScreenshotUrl} style={{ width: "100%", borderRadius: 3, maxHeight: 180 }} />
              </View>
              <View style={{ flex: 1 }}>
                <Text style={s.screenshotLabel}>{comp.competitorName}</Text>
                <Image src={comp.homepageComparison.competitorScreenshotUrl} style={{ width: "100%", borderRadius: 3, maxHeight: 180 }} />
              </View>
            </View>
          ) : null}

          {/* Differences table */}
          {comp.homepageComparison.differences.length > 0 && (
            <View style={s.table}>
              <View style={s.headerRow}>
                <Text style={[s.colHeader, { width: 14 }]}>#</Text>
                <Text style={[s.colHeader, { width: 60 }]}>CATEGORY</Text>
                <Text style={[s.colHeader, { flex: 1.5 }]}>BRAND</Text>
                <Text style={[s.colHeader, { flex: 1.5 }]}>COMPETITOR</Text>
                <Text style={[s.colHeader, { width: 50 }]}>IMPACT</Text>
              </View>
              {comp.homepageComparison.differences.map((d, di) => {
                const { bg, fg } = IMPACT_COLORS[d.impact];
                return (
                  <View key={di} style={[s.tableRow, di % 2 === 1 ? s.rowAlt : {}]} wrap={false}>
                    <Text style={[s.cellText, { width: 14 }]}>{d.number}</Text>
                    <Text style={[s.cellMuted, { width: 60 }]}>{CATEGORY_LABEL[d.category]}</Text>
                    <Text style={[s.cellMuted, { flex: 1.5 }]}>{d.brandObservation.slice(0, 80)}</Text>
                    <Text style={[s.cellText, { flex: 1.5 }]}>{d.competitorObservation.slice(0, 80)}</Text>
                    <View style={{ width: 50 }}>
                      <View style={[s.badge, { backgroundColor: bg }]}>
                        <Text style={{ fontSize: 6, color: fg, fontFamily: "Helvetica-Bold" }}>{d.impact}</Text>
                      </View>
                    </View>
                  </View>
                );
              })}
            </View>
          )}
        </View>
      ))}

      <Text style={s.disclosureText}>{cvc.patentRelevance}</Text>
    </View>
  );
}
