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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subtext: { ...S.small, marginBottom: 20 },
  overallRow: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 22,
    gap: 20,
  },
  bigScore: { fontSize: 72, fontFamily: "Helvetica-Bold", lineHeight: 1 },
  denom: { fontSize: 18, color: C.muted, paddingBottom: 10, alignSelf: "flex-end" },
  scoreContext: { flex: 1, paddingLeft: 4 },
  scoreContextLabel: { ...S.label, marginBottom: 6 },
  barBg: { backgroundColor: C.border, borderRadius: 3, height: 6, width: "100%" },
  barFill: { height: 6, borderRadius: 3, position: "absolute", top: 0, left: 0 },
  // Dimension rows
  dimSection: { marginTop: 4 },
  dimSectionLabel: { ...S.label, marginBottom: 10 },
  dimRow: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 10,
    gap: 8,
  },
  dimLabelCol: { width: 110 },
  dimNameWeight: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink },
  dimWeight: { fontSize: 8, color: C.muted },
  dimBarCol: { flex: 1 },
  dimBarBg: { backgroundColor: C.border, borderRadius: 3, height: 8, width: "100%" },
  dimBarFill: { height: 8, borderRadius: 3, position: "absolute", top: 0, left: 0 },
  dimScoreText: { width: 30, fontSize: 11, fontFamily: "Helvetica-Bold", textAlign: "right" },
  dimRationale: { fontSize: 8, color: C.muted, lineHeight: 1.4, marginTop: 2 },
  naTag: { width: 30, fontSize: 9, color: C.caption, textAlign: "right" },
});

function scoreColor(n: number): string {
  if (n >= 80) return C.green;
  if (n >= 60) return C.amber;
  return C.red;
}

function overallColor(n: number): string {
  if (n >= 80) return C.green;
  if (n >= 65) return C.amber;
  return C.red;
}

function dimRationale(key: keyof DimensionScores, score: number): string {
  const rating = score >= 80 ? "strong" : score >= 60 ? "moderate" : "needs work";
  switch (key) {
    case "technicalSeo":
      return score >= 80
        ? "Crawlability, schema, and mobile signals are solid."
        : score >= 60
        ? "Minor technical gaps — sitemap, schema, or redirect issues present."
        : "Structural issues are limiting crawlability and indexing.";
    case "contentMetadata":
      return score >= 80
        ? "Good metadata coverage — opportunities to expand on thin and underperforming pages."
        : score >= 60
        ? "Some metadata gaps — missing or thin on key pages."
        : score >= 50
        ? "Significant metadata gaps reducing search snippet quality."
        : "Metadata assessment limited — crawl data unavailable. Score estimated from partial signals.";
    case "aiVisibility":
      return score >= 80
        ? "Strong AI surface presence — brand cited across multiple AI search contexts with solid schema and authority signals."
        : score >= 60
        ? "Moderate AI surface presence — schema coverage and domain authority signals need strengthening for broader AI citation."
        : "Low AI surface visibility — schema gaps and limited domain authority are reducing citation potential.";
    case "conversionOptimization":
      return score >= 80
        ? "Strong conversion pathways — multiple engagement mechanisms and good channel diversity detected."
        : score >= 60
        ? "Conversion pathways present but limited in scope. Expanding CTA coverage and channel diversity improves resilience."
        : "Conversion architecture needs strengthening — limited conversion pathways detected across key pages.";
    case "userEngagement":
      return score >= 80
        ? "Good content depth and page experience signals across key pages."
        : score >= 60
        ? "Mixed engagement signals — content depth or page experience gaps on some pages."
        : "Engagement signals are weak — thin content and limited internal structure reduce dwell time.";
    default:
      return "";
  }
}

interface DimRowProps {
  label: string;
  weight: string;
  score: number | null;
  dimKey: keyof DimensionScores;
}

function DimRow({ label, weight, score, dimKey }: DimRowProps) {
  if (score == null) {
    return (
      <View style={s.dimRow}>
        <View style={s.dimLabelCol}>
          <Text style={s.dimNameWeight}>{label}</Text>
          <Text style={s.dimWeight}>{weight}</Text>
        </View>
        <View style={s.dimBarCol}>
          <View style={s.dimBarBg} />
        </View>
        <Text style={s.naTag}>N/A</Text>
      </View>
    );
  }

  const color = scoreColor(score);
  const pct = Math.min(100, score);
  const rationale = dimRationale(dimKey, score);

  return (
    <View style={s.dimRow}>
      <View style={s.dimLabelCol}>
        <Text style={s.dimNameWeight}>{label}</Text>
        <Text style={s.dimWeight}>{weight}</Text>
      </View>
      <View style={s.dimBarCol}>
        <View style={[s.dimBarBg, { position: "relative" }]}>
          <View style={[s.dimBarFill, { width: `${pct}%`, backgroundColor: color }]} />
        </View>
        {rationale ? <Text style={s.dimRationale}>{rationale}</Text> : null}
      </View>
      <Text style={[s.dimScoreText, { color }]}>{score}</Text>
    </View>
  );
}

interface Props {
  seo: SeoSection;
}

export function ScoreSection({ seo }: Props) {
  const score = seo.healthScore;
  const color = overallColor(score);
  const dim = seo.dimensionScores as DimensionScores | undefined;
  const pct = Math.min(100, score);

  return (
    <View>
      <Text style={s.heading}>SEO Health Score</Text>
      <Text style={s.subtext}>Composite score across technical, content, and engagement dimensions.</Text>

      <View style={s.overallRow}>
        <View style={{ flexDirection: "row", alignItems: "baseline" }}>
          <Text style={[s.bigScore, { color }]}>{score}</Text>
          <Text style={s.denom}> /100</Text>
        </View>
        <View style={s.scoreContext}>
          <Text style={s.scoreContextLabel}>Overall Health</Text>
          <View style={s.barBg}>
            <View style={[s.barFill, { width: `${pct}%`, backgroundColor: color }]} />
          </View>
          <Text style={{ ...S.caption, marginTop: 3 }}>
            {score >= 80
              ? "Strong across key dimensions — targeted improvements available."
              : score >= 65
              ? "Solid foundation with meaningful gaps to address."
              : score >= 50
              ? "Needs work — structural and content issues reducing organic performance."
              : "Critical gaps limiting search visibility and AI surface presence."}
          </Text>
        </View>
      </View>

      {dim && (
        <View style={s.dimSection}>
          <Text style={s.dimSectionLabel}>Score Breakdown</Text>
          <DimRow label="Technical SEO" weight="40% weight" score={dim.technicalSeo} dimKey="technicalSeo" />
          <DimRow label="Content & Metadata" weight="20% weight" score={dim.contentMetadata} dimKey="contentMetadata" />
          <DimRow label="AI Visibility" weight="20% weight" score={dim.aiVisibility} dimKey="aiVisibility" />
          <DimRow label="Conversion" weight="10% weight" score={dim.conversionOptimization} dimKey="conversionOptimization" />
          <DimRow label="Engagement" weight="10% weight" score={dim.userEngagement} dimKey="userEngagement" />
        </View>
      )}
    </View>
  );
}
