import { View, Text, Image, StyleSheet } from "@react-pdf/renderer";
import { C, S } from "../styles";
import type { MobileFirstAudit, MobileFinding, MobileDimension } from "../../../mobile-first/types";

const TIER_COLORS: Record<MobileFirstAudit["scoreTier"], { score: string; bg: string; text: string }> = {
  excellent:        { score: "#10b981", bg: "#d1fae5", text: "#065f46" },
  good:             { score: "#3b82f6", bg: "#dbeafe", text: "#1e40af" },
  needs_improvement:{ score: "#f59e0b", bg: "#fef3c7", text: "#92400e" },
  poor:             { score: "#ef4444", bg: "#fee2e2", text: "#991b1b" },
};

const SEV_COLORS: Record<MobileFinding["severity"], { bg: string; text: string }> = {
  critical: { bg: "#fee2e2", text: "#991b1b" },
  high:     { bg: "#ffedd5", text: "#9a3412" },
  moderate: { bg: "#fef3c7", text: "#92400e" },
  low:      { bg: "#f1f5f9", text: "#475569" },
};

const DIM_LABELS: Record<MobileDimension, string> = {
  viewport:              "Viewport",
  touch_targets:         "Touch Targets",
  mobile_schema:         "Mobile Schema",
  amp:                   "AMP",
  above_fold_composition:"Above-Fold",
};

const s = StyleSheet.create({
  heading:      { ...S.h2, marginBottom: 4 },
  subheading:   { ...S.small, color: C.muted, marginBottom: 12 },
  heroBox:      { flexDirection: "row", alignItems: "center", gap: 12, backgroundColor: C.surface, borderRadius: 4, padding: 10, marginBottom: 14, borderWidth: 0.75, borderColor: C.border },
  heroScore:    { fontSize: 34, fontFamily: "Helvetica-Bold", width: 58, textAlign: "center" },
  heroRight:    { flex: 1 },
  tierRow:      { flexDirection: "row", alignItems: "center", gap: 6, marginBottom: 5 },
  tierPill:     { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2 },
  tierPillText: { fontSize: 7, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  barBg:        { height: 4, backgroundColor: "#e2e8f0", borderRadius: 2, marginBottom: 5 },
  barFill:      { height: 4, borderRadius: 2 },
  statsRow:     { flexDirection: "row", gap: 12 },
  statItem:     { flex: 1 },
  statVal:      { fontSize: 13, fontFamily: "Helvetica-Bold", color: C.ink },
  statLabel:    { fontSize: 7, color: C.muted, marginTop: 1 },
  sectionLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 7 },
  dimGrid:      { flexDirection: "row", flexWrap: "wrap", marginHorizontal: -3, marginBottom: 14 },
  dimCard:      { width: "18%", marginHorizontal: "1%", marginBottom: 6, borderWidth: 0.75, borderColor: C.border, borderRadius: 3, padding: 6, alignItems: "center" },
  dimName:      { fontSize: 6.5, color: C.muted, textAlign: "center", marginBottom: 3 },
  dimCount:     { fontSize: 10, fontFamily: "Helvetica-Bold", color: C.ink },
  dimCrit:      { fontSize: 6.5, color: "#ef4444", marginTop: 2 },
  findingCard:  { borderWidth: 0.75, borderColor: C.border, borderRadius: 3, padding: 7, marginBottom: 6 },
  findingTop:   { flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 4 },
  findingTitle: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.ink, flex: 1 },
  sevPill:      { borderRadius: 2, paddingHorizontal: 4, paddingVertical: 1.5 },
  sevText:      { fontSize: 6, fontFamily: "Helvetica-Bold", letterSpacing: 0.4 },
  findingDetail:{ fontSize: 7.5, color: C.body, lineHeight: 1.4, marginBottom: 3 },
  findingRec:   { fontSize: 7, color: C.body, lineHeight: 1.35, backgroundColor: "#f8fafc", borderRadius: 2, padding: 4 },
  pageBox:      { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 9, marginBottom: 12 },
  pageHeader:   { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 8 },
  pageLabel:    { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink },
  pageScore:    { fontSize: 9, fontFamily: "Helvetica-Bold" },
  pageMetaRow:  { flexDirection: "row", gap: 10, marginBottom: 8 },
  pageMetaItem: { flex: 1, borderWidth: 0.5, borderColor: C.border, borderRadius: 2, padding: 4 },
  pageMetaKey:  { fontSize: 6, color: C.muted, marginBottom: 1 },
  pageMetaVal:  { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.ink },
  thumbImg:     { width: 90, height: 120, borderRadius: 3, borderWidth: 0.75, borderColor: C.border },
  pageContent:  { flexDirection: "row", gap: 8 },
  pageLeft:     { flex: 1 },
  notesBox:     { backgroundColor: "#eff6ff", borderRadius: 3, padding: 6, marginTop: 8 },
  notesLabel:   { fontSize: 7, fontFamily: "Helvetica-Bold", color: "#1e40af", marginBottom: 3 },
  notesText:    { fontSize: 7, color: "#1e3a5f", lineHeight: 1.35 },
  footerBox:    { borderTopWidth: 0.75, borderColor: C.border, paddingTop: 8, marginTop: 14 },
  footerText:   { fontSize: 7, color: C.muted, lineHeight: 1.4 },
});

function scoreColor(score: number): string {
  if (score >= 85) return "#10b981";
  if (score >= 65) return "#3b82f6";
  if (score >= 45) return "#f59e0b";
  return "#ef4444";
}

function metaStatus(ok: boolean | null | undefined, okLabel = "Pass", failLabel = "Fail"): string {
  if (ok === true) return okLabel;
  if (ok === false) return failLabel;
  return "N/A";
}

interface Props {
  mobileFirstAudit: MobileFirstAudit;
}

export function MobileFirstAuditPage({ mobileFirstAudit }: Props) {
  const tierColors = TIER_COLORS[mobileFirstAudit.scoreTier];
  const tierLabel =
    mobileFirstAudit.scoreTier === "needs_improvement" ? "Needs Improvement" :
    mobileFirstAudit.scoreTier.charAt(0).toUpperCase() + mobileFirstAudit.scoreTier.slice(1);
  const criticalCount = mobileFirstAudit.topPriorityFindings.filter((f) => f.severity === "critical").length;

  return (
    <View>
      <Text style={s.heading}>Mobile Usability Evaluation</Text>
      <Text style={s.subheading}>
        {mobileFirstAudit.pagesEvaluated} page{mobileFirstAudit.pagesEvaluated !== 1 ? "s" : ""} evaluated
        {" "}&middot; {mobileFirstAudit.windowDate.slice(0, 10)}
      </Text>

      {/* Hero */}
      <View style={s.heroBox}>
        <Text style={[s.heroScore, { color: tierColors.score }]}>
          {mobileFirstAudit.overallMobileScore}
        </Text>
        <View style={s.heroRight}>
          <View style={s.tierRow}>
            <View style={[s.tierPill, { backgroundColor: tierColors.bg }]}>
              <Text style={[s.tierPillText, { color: tierColors.text }]}>{tierLabel}</Text>
            </View>
          </View>
          <View style={s.barBg}>
            <View style={[s.barFill, { width: `${mobileFirstAudit.overallMobileScore}%`, backgroundColor: tierColors.score }]} />
          </View>
          <View style={s.statsRow}>
            <View style={s.statItem}>
              <Text style={s.statVal}>{mobileFirstAudit.pagesEvaluated}</Text>
              <Text style={s.statLabel}>Pages Evaluated</Text>
            </View>
            <View style={s.statItem}>
              <Text style={s.statVal}>{mobileFirstAudit.topPriorityFindings.length}</Text>
              <Text style={s.statLabel}>Priority Findings</Text>
            </View>
            <View style={s.statItem}>
              <Text style={[s.statVal, { color: criticalCount > 0 ? "#ef4444" : C.ink }]}>{criticalCount}</Text>
              <Text style={s.statLabel}>Critical Issues</Text>
            </View>
          </View>
        </View>
      </View>

      {/* Dimension breakdown */}
      <Text style={s.sectionLabel}>Dimension Breakdown</Text>
      <View style={s.dimGrid}>
        {(Object.keys(DIM_LABELS) as MobileDimension[]).map((dim) => {
          const bd = mobileFirstAudit.dimensionBreakdown[dim];
          return (
            <View key={dim} style={s.dimCard}>
              <Text style={s.dimName}>{DIM_LABELS[dim]}</Text>
              <Text style={s.dimCount}>{bd.findingCount}</Text>
              {bd.criticalCount > 0 && (
                <Text style={s.dimCrit}>{bd.criticalCount} critical</Text>
              )}
            </View>
          );
        })}
      </View>

      {/* Top priority findings */}
      {mobileFirstAudit.topPriorityFindings.length > 0 && (
        <View>
          <Text style={s.sectionLabel}>Priority Findings</Text>
          {mobileFirstAudit.topPriorityFindings.map((finding) => {
            const sevCfg = SEV_COLORS[finding.severity];
            return (
              <View key={finding.id} style={s.findingCard}>
                <View style={s.findingTop}>
                  <Text style={s.findingTitle}>{finding.title}</Text>
                  <View style={[s.sevPill, { backgroundColor: sevCfg.bg }]}>
                    <Text style={[s.sevText, { color: sevCfg.text }]}>
                      {finding.severity.charAt(0).toUpperCase() + finding.severity.slice(1)}
                    </Text>
                  </View>
                </View>
                <Text style={s.findingDetail}>{finding.detail}</Text>
                {finding.recommendation && (
                  <View style={s.findingRec}>
                    <Text style={{ fontSize: 7, color: C.body, lineHeight: 1.35 }}>
                      Fix: {finding.recommendation}
                    </Text>
                  </View>
                )}
              </View>
            );
          })}
        </View>
      )}

      {/* Per-page details */}
      {mobileFirstAudit.perPageEvaluations.slice(0, 3).map((ev) => (
        <View key={ev.pageUrl} style={s.pageBox} wrap={false}>
          <View style={s.pageHeader}>
            <Text style={s.pageLabel}>{ev.pageLabel}</Text>
            <Text style={[s.pageScore, { color: scoreColor(ev.mobileScore) }]}>
              {ev.mobileScore}/100
            </Text>
          </View>
          <View style={s.pageContent}>
            {ev.mobileScreenshotUrl && (
              <Image src={ev.mobileScreenshotUrl} style={s.thumbImg} />
            )}
            <View style={s.pageLeft}>
              <View style={s.pageMetaRow}>
                <View style={s.pageMetaItem}>
                  <Text style={s.pageMetaKey}>Viewport</Text>
                  <Text style={s.pageMetaVal}>{metaStatus(ev.viewport.isOptimal, "Optimal", ev.viewport.hasViewportMeta ? "Issues" : "Missing")}</Text>
                </View>
                <View style={s.pageMetaItem}>
                  <Text style={s.pageMetaKey}>Touch Pass Rate</Text>
                  <Text style={s.pageMetaVal}>{ev.touchTargets.passRate}%</Text>
                </View>
                <View style={s.pageMetaItem}>
                  <Text style={s.pageMetaKey}>Mobile Schema</Text>
                  <Text style={s.pageMetaVal}>{metaStatus(ev.mobileSchema.hasMobileSpecificSchema, "Present", "Missing")}</Text>
                </View>
                <View style={s.pageMetaItem}>
                  <Text style={s.pageMetaKey}>Above-Fold</Text>
                  <Text style={s.pageMetaVal}>{ev.aboveFoldComposition.score}/100</Text>
                </View>
              </View>
              {ev.findings.slice(0, 2).map((f) => (
                <Text key={f.id} style={{ fontSize: 7.5, color: C.body, lineHeight: 1.35, marginBottom: 3 }}>
                  [{f.severity.toUpperCase()}] {f.title}: {f.detail}
                </Text>
              ))}
            </View>
          </View>
          {ev.aboveFoldComposition.verticalNotes.length > 0 && (
            <View style={s.notesBox}>
              <Text style={s.notesLabel}>Industry Notes</Text>
              {ev.aboveFoldComposition.verticalNotes.map((note, i) => (
                <Text key={i} style={s.notesText}>{note}</Text>
              ))}
            </View>
          )}
        </View>
      ))}

      {/* Methodology footer */}
      <View style={s.footerBox}>
        <Text style={s.footerText}>
          Mobile usability evaluation analyzes page HTML for viewport configuration,
          interactive element sizing, structured data coverage, and above-fold conversion
          element presence. Mobile screenshots are reused from the visual annotation capture.
          No third-party tools or paid APIs are used in this evaluation.
        </Text>
      </View>
    </View>
  );
}
