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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, color: C.muted, marginBottom: 14 },
  // Stats strip
  statsRow: { flexDirection: "row", gap: 6, marginBottom: 14 },
  statBox: { flex: 1, borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8, alignItems: "center" },
  statValue: { fontSize: 14, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 2 },
  statLabel: { fontSize: 7, color: C.muted, textAlign: "center" },
  // Section label
  sectionLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 8 },
  // Per-query rows
  queryCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, marginBottom: 6, overflow: "hidden" },
  queryHeader: { backgroundColor: C.surface, paddingHorizontal: 8, paddingVertical: 5, borderBottomWidth: 0.5, borderBottomColor: C.border, flexDirection: "row", justifyContent: "space-between", alignItems: "center" },
  queryText: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, flex: 1 },
  queryRank: { fontSize: 7.5, color: C.muted },
  featureRow: { flexDirection: "row", flexWrap: "wrap", gap: 4, paddingHorizontal: 8, paddingVertical: 6 },
  featurePill: { borderRadius: 3, paddingHorizontal: 6, paddingVertical: 2, flexDirection: "row", alignItems: "center", gap: 3 },
  featurePillText: { fontSize: 7, fontFamily: "Helvetica-Bold" },
  // Opportunities
  oppCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8, marginBottom: 8 },
  oppHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 4 },
  oppQuery: { fontSize: 7.5, color: C.muted, marginBottom: 2 },
  oppFeature: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink },
  oppRight: { flexDirection: "row", gap: 5, alignItems: "center" },
  diffBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  diffText: { fontSize: 7, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  oppRationale: { fontSize: 8, color: C.body, lineHeight: 1.4, marginBottom: 5 },
  pathBox: { backgroundColor: C.surface, borderRadius: 3, paddingHorizontal: 7, paddingVertical: 5 },
  pathLabel: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted },
  pathText: { fontSize: 7.5, color: C.body, lineHeight: 1.3 },
});

const STATUS_COLORS: Record<string, { bg: string; text: string; icon: string }> = {
  eligible: { bg: "#d1fae5", text: "#065f46", icon: "✓" },
  partial: { bg: "#fef3c7", text: "#92400e", icon: "◑" },
  not_eligible: { bg: "#fee2e2", text: "#991b1b", icon: "✗" },
};

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

interface Props {
  aiSnippetEligibility: AiSnippetEligibility;
}

export function AiSnippetEligibilityPage({ aiSnippetEligibility }: Props) {
  const { perQuery, topOpportunities, aggregateStats } = aiSnippetEligibility;

  return (
    <View>
      <Text style={s.heading}>AI Snippet Eligibility Analysis</Text>
      <Text style={s.subheading}>SERP feature presence and capture opportunities across {aggregateStats.totalQueriesAnalyzed} tracked queries</Text>

      {/* Stats strip */}
      <View style={s.statsRow}>
        {[
          { label: "Queries Analyzed", value: String(aggregateStats.totalQueriesAnalyzed) },
          { label: "With Eligible Features", value: String(aggregateStats.queriesWithEligibleFeatures) },
          { label: "Features Present", value: String(aggregateStats.totalFeaturesPresent) },
          { label: "Eligibility Rate", value: `${aggregateStats.eligibilityRatePercent}%` },
        ].map((stat, i) => (
          <View key={i} style={s.statBox}>
            <Text style={s.statValue}>{stat.value}</Text>
            <Text style={s.statLabel}>{stat.label}</Text>
          </View>
        ))}
      </View>

      {/* Per-query matrix */}
      {perQuery.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>Per-Query Snippet Matrix</Text>
          {perQuery.slice(0, 8).map((q, qi) => (
            <View key={qi} style={s.queryCard} wrap={false}>
              <View style={s.queryHeader}>
                <Text style={s.queryText}>{q.query.length > 55 ? q.query.slice(0, 54) + "…" : q.query}</Text>
                {q.brandRanking != null && (
                  <Text style={s.queryRank}>rank #{q.brandRanking}</Text>
                )}
              </View>
              <View style={s.featureRow}>
                {q.perFeatureEligibility.map((f, fi) => {
                  const cfg = STATUS_COLORS[f.eligibilityStatus] ?? STATUS_COLORS.not_eligible;
                  return (
                    <View key={fi} style={[s.featurePill, { backgroundColor: cfg.bg }]}>
                      <Text style={[s.featurePillText, { color: cfg.text }]}>{cfg.icon} {f.feature}</Text>
                    </View>
                  );
                })}
              </View>
            </View>
          ))}
        </View>
      )}

      {/* Top opportunities */}
      {topOpportunities.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>Top Capture Opportunities</Text>
          {topOpportunities.map((opp, i) => {
            const matchedQuery = perQuery.find((q) => q.query === opp.query);
            const matchedFeature = matchedQuery?.perFeatureEligibility.find((f) => f.feature === opp.feature);
            const diffColor = DIFF_COLORS[matchedFeature?.implementationDifficulty ?? "moderate"] ?? DIFF_COLORS.moderate;
            return (
              <View key={i} style={s.oppCard} wrap={false}>
                <View style={s.oppHeader}>
                  <View style={{ flex: 1 }}>
                    <Text style={s.oppQuery}>"{opp.query}"</Text>
                    <Text style={s.oppFeature}>{opp.feature}</Text>
                  </View>
                  <View style={[s.diffBadge, { backgroundColor: diffColor.bg }]}>
                    <Text style={[s.diffText, { color: diffColor.text }]}>
                      {(matchedFeature?.implementationDifficulty ?? "moderate").toUpperCase()}
                    </Text>
                  </View>
                </View>
                <Text style={s.oppRationale}>{opp.rationale}</Text>
                <View style={s.pathBox}>
                  <Text style={s.pathLabel}>QUICKEST PATH</Text>
                  <Text style={s.pathText}>{opp.quickestPath}</Text>
                </View>
              </View>
            );
          })}
        </View>
      )}
    </View>
  );
}
