import { View, Text, StyleSheet } from "@react-pdf/renderer";
import { C, S } from "../styles";
import type { PageSpeedInsights, CoreWebVital, WebVitalGrade } from "../../../page-speed/types";

const TIER_COLORS: Record<PageSpeedInsights["overallScoreTier"], { 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 GRADE_COLORS: Record<WebVitalGrade, { bg: string; text: string }> = {
  good:             { bg: "#d1fae5", text: "#065f46" },
  needs_improvement:{ bg: "#fef3c7", text: "#92400e" },
  poor:             { bg: "#fee2e2", text: "#991b1b" },
};

const s = StyleSheet.create({
  heading:       { ...S.h2, marginBottom: 4 },
  subheading:    { ...S.small, color: C.muted, marginBottom: 12 },
  heroBox:       { backgroundColor: C.surface, borderRadius: 4, padding: 10, marginBottom: 14, borderWidth: 0.75, borderColor: C.border },
  heroTop:       { flexDirection: "row", alignItems: "center", gap: 12, marginBottom: 10 },
  tierPill:      { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2 },
  tierPillText:  { fontSize: 7, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  heroRight:     { flex: 1 },
  heroTitle:     { fontSize: 11, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 3 },
  heroSub:       { fontSize: 7.5, color: C.muted },
  impactBox:     { alignItems: "center", backgroundColor: "#fee2e2", borderRadius: 3, padding: 8, borderWidth: 0.75, borderColor: "#fca5a5", minWidth: 100 },
  impactLabel:   { fontSize: 6.5, fontFamily: "Helvetica-Bold", color: "#991b1b", letterSpacing: 0.5, marginBottom: 2 },
  impactValue:   { fontSize: 18, fontFamily: "Helvetica-Bold", color: "#dc2626" },
  impactSub:     { fontSize: 6.5, color: "#9b1c1c", marginTop: 1 },
  statsRow:      { flexDirection: "row", gap: 10 },
  statBox:       { flex: 1, borderWidth: 0.5, borderColor: C.border, borderRadius: 3, padding: 6 },
  statVal:       { fontSize: 13, fontFamily: "Helvetica-Bold", color: C.ink },
  statLabel:     { fontSize: 6.5, color: C.muted, marginTop: 1 },
  sectionLabel:  { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textTransform: "uppercase", marginBottom: 8 },
  cwvGrid:       { flexDirection: "row", gap: 6, marginBottom: 14 },
  cwvCard:       { flex: 1, borderRadius: 3, padding: 6, borderWidth: 0.75, alignItems: "center" },
  cwvMetric:     { fontSize: 7.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.5 },
  cwvGrade:      { fontSize: 6.5, marginTop: 2 },
  pageBox:       { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 9, marginBottom: 10 },
  pageHeader:    { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 8 },
  pageTitle:     { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink },
  pageScore:     { fontSize: 9, fontFamily: "Helvetica-Bold" },
  vitalRow:      { flexDirection: "row", gap: 5, marginBottom: 8 },
  vitalCard:     { flex: 1, borderRadius: 3, padding: 5, borderWidth: 0.75 },
  vitalMetric:   { fontSize: 6.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.4, marginBottom: 2 },
  vitalValue:    { fontSize: 11, fontFamily: "Helvetica-Bold", color: C.ink },
  vitalLabel:    { fontSize: 5.5, color: C.muted, marginTop: 1 },
  tableBox:      { borderWidth: 0.75, borderColor: C.border, borderRadius: 3, overflow: "hidden", marginBottom: 7 },
  tableHeader:   { flexDirection: "row", backgroundColor: C.surface, paddingHorizontal: 6, paddingVertical: 3 },
  tableRow:      { flexDirection: "row", borderTopWidth: 0.5, borderColor: C.border, paddingHorizontal: 6, paddingVertical: 3 },
  tableCell:     { fontSize: 7, color: C.body },
  tableCellMono: { fontSize: 6.5, color: C.body, fontFamily: "Courier" },
  tableCellHdr:  { fontSize: 6.5, color: C.muted, fontFamily: "Helvetica-Bold", letterSpacing: 0.3 },
  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 >= 90) return "#10b981";
  if (score >= 70) return "#3b82f6";
  if (score >= 50) return "#f59e0b";
  return "#ef4444";
}

function formatVitalValue(vital: CoreWebVital): string {
  const value = vital.fieldValue ?? vital.labValue;
  if (value == null) return "N/A";
  if (vital.unit === "score") return value.toFixed(2);
  if (vital.unit === "s") return `${(value / 1000).toFixed(1)}s`;
  return `${Math.round(value)}ms`;
}

function truncatePath(url: string, max = 55): string {
  try {
    const parsed = new URL(url);
    const path = parsed.pathname + (parsed.search ? parsed.search.slice(0, 20) : "");
    return path.length > max ? path.slice(0, max) + "..." : path;
  } catch {
    return url.length > max ? url.slice(0, max) + "..." : url;
  }
}

interface Props {
  pageSpeedInsights: PageSpeedInsights;
}

export function PageSpeedInsightsPage({ pageSpeedInsights }: Props) {
  const tierColors = TIER_COLORS[pageSpeedInsights.overallScoreTier];
  const tierLabel =
    pageSpeedInsights.overallScoreTier === "needs_improvement" ? "Needs Improvement" :
    pageSpeedInsights.overallScoreTier.charAt(0).toUpperCase() + pageSpeedInsights.overallScoreTier.slice(1);
  const hasRevenueLoss = pageSpeedInsights.estimatedMonthlyRevenueLoss > 0;

  return (
    <View>
      <Text style={s.heading}>Page Load Performance Analysis</Text>
      <Text style={s.subheading}>
        {pageSpeedInsights.pagesAnalyzed} page{pageSpeedInsights.pagesAnalyzed !== 1 ? "s" : ""} analyzed
        {" "}&middot; {pageSpeedInsights.windowDate.slice(0, 10)}
      </Text>

      {/* Hero */}
      <View style={s.heroBox}>
        <View style={s.heroTop}>
          <View style={s.heroRight}>
            <View style={[s.tierPill, { backgroundColor: tierColors.bg, marginBottom: 5, alignSelf: "flex-start" }]}>
              <Text style={[s.tierPillText, { color: tierColors.text }]}>{tierLabel}</Text>
            </View>
            <Text style={s.heroTitle}>Performance Tier: {tierLabel}</Text>
            <Text style={s.heroSub}>
              {pageSpeedInsights.pagesAnalyzed} page{pageSpeedInsights.pagesAnalyzed !== 1 ? "s" : ""} evaluated on mobile configuration
            </Text>
          </View>
          {hasRevenueLoss && (
            <View style={s.impactBox}>
              <Text style={s.impactLabel}>EST. MONTHLY REVENUE IMPACT</Text>
              <Text style={s.impactValue}>${pageSpeedInsights.estimatedMonthlyRevenueLoss.toLocaleString()}</Text>
              <Text style={s.impactSub}>~{pageSpeedInsights.estimatedMonthlyTrafficLoss.toLocaleString()} sessions/mo</Text>
            </View>
          )}
        </View>
        <View style={s.statsRow}>
          <View style={s.statBox}>
            <Text style={s.statVal}>{pageSpeedInsights.pagesAnalyzed}</Text>
            <Text style={s.statLabel}>Pages Analyzed</Text>
          </View>
          <View style={s.statBox}>
            <Text style={[s.statVal, { color: tierColors.score }]}>{tierLabel}</Text>
            <Text style={s.statLabel}>Performance Tier</Text>
          </View>
          <View style={s.statBox}>
            <Text style={s.statVal}>{pageSpeedInsights.topRenderBlockingResources.length}</Text>
            <Text style={s.statLabel}>Render-Blocking Resources</Text>
          </View>
          <View style={s.statBox}>
            <Text style={s.statVal}>{pageSpeedInsights.topImageOpportunities.length}</Text>
            <Text style={s.statLabel}>Image Opportunities</Text>
          </View>
        </View>
      </View>

      {/* Aggregate CWV grid */}
      <Text style={s.sectionLabel}>Core Vitals Summary</Text>
      <View style={s.cwvGrid}>
        {(["LCP", "INP", "CLS", "FCP", "TTFB"] as const).map((metric) => {
          const grade = pageSpeedInsights.aggregateCwvGrades[metric];
          const gradeColors = grade ? GRADE_COLORS[grade] : { bg: C.surface, text: C.muted };
          const gradeLabel = grade === "needs_improvement" ? "Needs Work" : grade ? grade.charAt(0).toUpperCase() + grade.slice(1) : "N/A";
          return (
            <View key={metric} style={[s.cwvCard, { backgroundColor: gradeColors.bg, borderColor: "#e2e8f0" }]}>
              <Text style={[s.cwvMetric, { color: gradeColors.text }]}>{metric}</Text>
              <Text style={[s.cwvGrade, { color: gradeColors.text }]}>{gradeLabel}</Text>
            </View>
          );
        })}
      </View>

      {/* Per-page breakdowns */}
      {pageSpeedInsights.perPageAnalyses.slice(0, 3).map((analysis) => (
        <View key={analysis.pageUrl} style={s.pageBox} wrap={false}>
          <View style={s.pageHeader}>
            <Text style={s.pageTitle}>{analysis.pageLabel}</Text>
            <Text style={[s.pageScore, { color: scoreColor(analysis.overallScore) }]}>
              {analysis.overallScore}/100
            </Text>
          </View>

          {/* Vital cards */}
          <View style={s.vitalRow}>
            {analysis.coreWebVitals.slice(0, 5).map((vital) => {
              const grade = vital.fieldGrade ?? vital.labGrade;
              const gradeCfg = grade ? GRADE_COLORS[grade] : { bg: C.surface, text: C.muted };
              return (
                <View key={vital.metric} style={[s.vitalCard, { backgroundColor: gradeCfg.bg, borderColor: "#e2e8f0" }]}>
                  <Text style={[s.vitalMetric, { color: gradeCfg.text }]}>{vital.metric}</Text>
                  <Text style={s.vitalValue}>{formatVitalValue(vital)}</Text>
                  <Text style={s.vitalLabel}>{vital.displayName.split(" ").slice(0, 2).join(" ")}</Text>
                </View>
              );
            })}
          </View>

          {/* Render-blocking resources */}
          {analysis.renderBlockingResources.length > 0 && (
            <View>
              <Text style={[s.sectionLabel, { marginBottom: 4 }]}>Render-Blocking Resources</Text>
              <View style={s.tableBox}>
                <View style={s.tableHeader}>
                  <Text style={[s.tableCellHdr, { flex: 1 }]}>Resource</Text>
                  <Text style={[s.tableCellHdr, { width: 60 }]}>Type</Text>
                  <Text style={[s.tableCellHdr, { width: 60, textAlign: "right" }]}>Delay (ms)</Text>
                </View>
                {analysis.renderBlockingResources.slice(0, 4).map((r, i) => (
                  <View key={i} style={s.tableRow}>
                    <Text style={[s.tableCellMono, { flex: 1 }]}>{truncatePath(r.url, 50)}</Text>
                    <Text style={[s.tableCell, { width: 60, textTransform: "capitalize" }]}>{r.resourceType}</Text>
                    <Text style={[s.tableCell, { width: 60, textAlign: "right", color: r.wastedMs > 500 ? "#f97316" : C.body }]}>
                      {r.wastedMs > 0 ? r.wastedMs.toLocaleString() : "--"}
                    </Text>
                  </View>
                ))}
              </View>
            </View>
          )}

          {/* Image opportunities */}
          {analysis.imageOpportunities.length > 0 && (
            <View>
              <Text style={[s.sectionLabel, { marginBottom: 4 }]}>Image Optimization Opportunities</Text>
              <View style={s.tableBox}>
                <View style={s.tableHeader}>
                  <Text style={[s.tableCellHdr, { flex: 1 }]}>Image</Text>
                  <Text style={[s.tableCellHdr, { width: 120 }]}>Issue</Text>
                  <Text style={[s.tableCellHdr, { width: 55, textAlign: "right" }]}>Savings</Text>
                </View>
                {analysis.imageOpportunities.slice(0, 3).map((opp, i) => (
                  <View key={i} style={s.tableRow}>
                    <Text style={[s.tableCellMono, { flex: 1 }]}>{truncatePath(opp.url, 40)}</Text>
                    <Text style={[s.tableCell, { width: 120 }]}>{opp.issue}</Text>
                    <Text style={[s.tableCell, { width: 55, textAlign: "right", color: "#f97316" }]}>
                      {opp.wastedKb} KB
                    </Text>
                  </View>
                ))}
              </View>
            </View>
          )}
        </View>
      ))}

      {/* Top cross-page render-blocking resources */}
      {pageSpeedInsights.topRenderBlockingResources.length > 0 && (
        <View wrap={false}>
          <Text style={s.sectionLabel}>Top Render-Blocking Resources (All Pages)</Text>
          <View style={s.tableBox}>
            <View style={s.tableHeader}>
              <Text style={[s.tableCellHdr, { flex: 1 }]}>Resource</Text>
              <Text style={[s.tableCellHdr, { width: 65 }]}>Type</Text>
              <Text style={[s.tableCellHdr, { width: 70, textAlign: "right" }]}>Max Delay (ms)</Text>
            </View>
            {pageSpeedInsights.topRenderBlockingResources.slice(0, 6).map((r, i) => (
              <View key={i} style={s.tableRow}>
                <Text style={[s.tableCellMono, { flex: 1 }]}>{truncatePath(r.url, 55)}</Text>
                <Text style={[s.tableCell, { width: 65, textTransform: "capitalize" }]}>{r.resourceType}</Text>
                <Text style={[s.tableCell, { width: 70, textAlign: "right", color: r.wastedMs > 500 ? "#f97316" : C.body }]}>
                  {r.wastedMs > 0 ? r.wastedMs.toLocaleString() : "--"}
                </Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Methodology footer */}
      <View style={s.footerBox}>
        <Text style={s.footerText}>
          Performance analysis uses a public speed evaluation API to capture lab-based
          Core Web Vitals (LCP, INP, CLS, FCP, TTFB) and real-user field data where
          available. Revenue and traffic impact estimates are directional projections
          based on industry conversion rate baselines and should not be treated as
          measurements. Analysis is conducted on mobile configuration using simulated
          mobile hardware. No paid APIs or third-party tools are billed for this section.
        </Text>
      </View>
    </View>
  );
}
