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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, color: C.muted, marginBottom: 12 },
  // Industry relevance pill
  relevancePill: { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2, alignSelf: "flex-start", marginBottom: 12 },
  relevancePillText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.8 },
  // Composite score
  scoreBox: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 10, marginBottom: 14, flexDirection: "row", alignItems: "center", justifyContent: "space-between" },
  scoreLabelText: { fontSize: 9.5, fontFamily: "Helvetica-Bold", color: C.ink },
  scoreBarRow: { flex: 1, marginHorizontal: 12 },
  scoreBarBg: { height: 5, backgroundColor: "#e2e8f0", borderRadius: 2 },
  scoreBarFill: { height: 5, borderRadius: 2 },
  scoreValue: { fontSize: 16, fontFamily: "Helvetica-Bold" },
  // Dimension grid 2x2
  dimGrid: { flexDirection: "row", flexWrap: "wrap", marginHorizontal: -4, marginBottom: 14 },
  dimCard: { width: "48%", marginHorizontal: "1%", marginBottom: 8, borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8 },
  dimHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 5 },
  dimLabel: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink },
  dimScore: { fontSize: 10, fontFamily: "Helvetica-Bold" },
  barBg: { height: 4, backgroundColor: "#e2e8f0", borderRadius: 2 },
  barFill: { height: 4, borderRadius: 2 },
  // Gaps section
  sectionLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 8 },
  gapCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8, marginBottom: 6 },
  gapHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 4 },
  gapDimBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  gapDimText: { fontSize: 6.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  gapRight: { flexDirection: "row", gap: 6, alignItems: "center" },
  diffBadge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  diffText: { fontSize: 6.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  liftText: { fontSize: 8, fontFamily: "Helvetica-Bold", color: "#059669" },
  gapTitle: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 3, lineHeight: 1.3 },
  gapDesc: { fontSize: 8, color: C.body, lineHeight: 1.4 },
  // Recommendations table
  recRow: { flexDirection: "row", borderBottomWidth: 0.5, borderBottomColor: C.border, paddingVertical: 5 },
  recTitle: { fontSize: 8, color: C.ink, flex: 3, lineHeight: 1.35 },
  recMeta: { fontSize: 7.5, color: C.muted, width: 55, textAlign: "right" },
  // Patent footer
  footerBox: { borderTopWidth: 0.5, borderTopColor: C.border, paddingTop: 8, marginTop: 8 },
  footerText: { fontSize: 7, color: C.muted, lineHeight: 1.4 },
});

const RELEVANCE_COLORS: Record<string, { bg: string; text: string }> = {
  high: { bg: "#d1fae5", text: "#065f46" },
  medium: { bg: "#fef3c7", text: "#92400e" },
  low: { bg: "#f1f5f9", text: "#475569" },
};

const DIM_COLORS: Record<string, string> = {
  "speakable-schema": "#7c3aed",
  "conversational-query": "#3b82f6",
  "faq-readability": "#f59e0b",
  "local-pack-signals": "#10b981",
};

const DIM_LABELS: Record<string, string> = {
  "speakable-schema": "Speakable Schema",
  "conversational-query": "Conversational Query",
  "faq-readability": "FAQ Readability",
  "local-pack-signals": "Local Pack Signals",
};

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

const IMPACT_LABELS: Record<string, string> = {
  high: "High impact",
  medium: "Medium impact",
  low: "Low impact",
};

const EFFORT_LABELS: Record<string, string> = {
  hour: "1 hr",
  day: "1 day",
  week: "1 wk",
};

function scoreTextColor(score: number): string {
  if (score >= 70) return "#10b981";
  if (score >= 45) return "#f59e0b";
  return "#ef4444";
}

function barColor(score: number): string {
  if (score >= 70) return "#10b981";
  if (score >= 45) return "#f59e0b";
  return "#ef4444";
}

const SUB_SCORE_ENTRIES: Array<{ key: keyof VoiceSearchEligibility["subScores"]; dim: string }> = [
  { key: "speakableSchema", dim: "speakable-schema" },
  { key: "conversationalQuery", dim: "conversational-query" },
  { key: "faqReadability", dim: "faq-readability" },
  { key: "localPackSignals", dim: "local-pack-signals" },
];

interface Props {
  voiceSearchEligibility: VoiceSearchEligibility;
}

export function VoiceSearchEligibilityPage({ voiceSearchEligibility }: Props) {
  const { compositeScore, industryRelevance, subScores, topGaps, recommendations, patentRelevance } = voiceSearchEligibility;
  const relevanceColor = RELEVANCE_COLORS[industryRelevance] ?? RELEVANCE_COLORS.medium!;
  const compositePct = Math.min(100, Math.max(0, compositeScore));

  return (
    <View>
      <Text style={s.heading}>Voice Search Eligibility</Text>
      <Text style={s.subheading}>Structural content signals that determine eligibility for AI voice assistant responses</Text>

      {/* Industry relevance pill */}
      <View style={[s.relevancePill, { backgroundColor: relevanceColor.bg }]}>
        <Text style={[s.relevancePillText, { color: relevanceColor.text }]}>
          {industryRelevance.toUpperCase()} INDUSTRY RELEVANCE
        </Text>
      </View>

      {/* Composite score */}
      <View style={s.scoreBox}>
        <Text style={s.scoreLabelText}>Composite Voice Search Score</Text>
        <View style={s.scoreBarRow}>
          <View style={s.scoreBarBg}>
            <View style={[s.scoreBarFill, { width: `${compositePct}%`, backgroundColor: barColor(compositeScore) }]} />
          </View>
        </View>
        <Text style={[s.scoreValue, { color: scoreTextColor(compositeScore) }]}>{compositeScore}/100</Text>
      </View>

      {/* Sub-score 2x2 grid */}
      <View style={s.dimGrid}>
        {SUB_SCORE_ENTRIES.map(({ key, dim }) => {
          const score = subScores[key];
          const pct = Math.min(100, Math.max(0, score));
          const color = DIM_COLORS[dim] ?? "#64748b";
          return (
            <View key={dim} style={s.dimCard} wrap={false}>
              <View style={s.dimHeader}>
                <Text style={s.dimLabel}>{DIM_LABELS[dim] ?? dim}</Text>
                <Text style={[s.dimScore, { color: scoreTextColor(score) }]}>{score}/100</Text>
              </View>
              <View style={s.barBg}>
                <View style={[s.barFill, { width: `${pct}%`, backgroundColor: color }]} />
              </View>
            </View>
          );
        })}
      </View>

      {/* Top gaps */}
      {topGaps.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>Top Gaps by Score Lift</Text>
          {topGaps.map((gap, i) => {
            const diffColor = DIFF_COLORS[gap.implementationDifficulty] ?? DIFF_COLORS.moderate!;
            return (
              <View key={i} style={s.gapCard} wrap={false}>
                <View style={s.gapHeader}>
                  <View style={[s.gapDimBadge, { backgroundColor: "#f1f5f9" }]}>
                    <Text style={[s.gapDimText, { color: "#475569" }]}>
                      {(DIM_LABELS[gap.dimension] ?? gap.dimension).toUpperCase()}
                    </Text>
                  </View>
                  <View style={s.gapRight}>
                    <View style={[s.diffBadge, { backgroundColor: diffColor.bg }]}>
                      <Text style={[s.diffText, { color: diffColor.text }]}>
                        {gap.implementationDifficulty.toUpperCase()}
                      </Text>
                    </View>
                    <Text style={s.liftText}>+{gap.estimatedScoreLift} pts</Text>
                  </View>
                </View>
                <Text style={s.gapTitle}>{gap.gap}</Text>
                <Text style={s.gapDesc}>{gap.impactDescription}</Text>
              </View>
            );
          })}
        </View>
      )}

      {/* Recommendations */}
      {recommendations.length > 0 && (
        <View style={{ marginTop: 10 }}>
          <Text style={s.sectionLabel}>Recommendations</Text>
          {recommendations.map((rec, i) => (
            <View key={i} style={s.recRow} wrap={false}>
              <Text style={s.recTitle}>{rec.title}</Text>
              <Text style={s.recMeta}>{IMPACT_LABELS[rec.impact]} / {EFFORT_LABELS[rec.effort]}</Text>
            </View>
          ))}
        </View>
      )}

      {/* Patent relevance footer */}
      <View style={s.footerBox}>
        <Text style={s.footerText}>{patentRelevance}</Text>
      </View>
    </View>
  );
}
