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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, marginBottom: 14, color: C.muted },
  // Stats strip
  statsRow: { flexDirection: "row", gap: 8, marginBottom: 14 },
  statCard: { flex: 1, borderRadius: 4, padding: 8, alignItems: "center" },
  statValue: { fontSize: 18, fontFamily: "Helvetica-Bold", marginBottom: 2 },
  statLabel: { fontSize: 7, color: C.muted },
  // Top priority list
  section: { marginBottom: 12 },
  sectionHeading: { fontSize: 9, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 6 },
  priorityCard: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 8, marginBottom: 6 },
  badgeRow: { flexDirection: "row", gap: 6, marginBottom: 4 },
  badge: { borderRadius: 2, paddingHorizontal: 5, paddingVertical: 1.5 },
  badgeText: { fontSize: 6.5, fontFamily: "Helvetica-Bold" },
  priorityLabel: { fontSize: 8.5, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 2 },
  priorityDesc: { fontSize: 7, color: C.muted, lineHeight: 1.4 },
  // Per-page
  pageSection: { marginBottom: 16 },
  pageLabelRow: { flexDirection: "row", gap: 8, alignItems: "center", marginBottom: 6 },
  pageTypeLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: C.ink },
  pageUrlText: { fontSize: 6.5, color: C.muted },
  screenshot: { width: "100%", borderRadius: 4, marginBottom: 8, objectFit: "cover", maxHeight: 320 },
  // Annotation table
  table: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, overflow: "hidden" },
  headerRow: { flexDirection: "row", backgroundColor: C.surface, paddingHorizontal: 6, paddingVertical: 3, borderBottomWidth: 0.75, borderBottomColor: C.border },
  tableRow: { flexDirection: "row", paddingHorizontal: 6, paddingVertical: 3, borderBottomWidth: 0.5, borderBottomColor: "#f1f5f9" },
  rowAlt: { backgroundColor: "#fafafa" },
  colHeader: { fontSize: 6, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.5 },
  cellText: { fontSize: 7, color: C.body },
  cellMuted: { fontSize: 6.5, color: C.muted },
  // Disclosure
  disclosureText: { fontSize: 7, color: C.muted, fontStyle: "italic", marginTop: 8 },
});

function severityColors(severity: string): { bg: string; fg: string } {
  switch (severity) {
    case "critical": return { bg: "#fee2e2", fg: "#dc2626" };
    case "high":     return { bg: "#ffedd5", fg: "#ea580c" };
    case "moderate": return { bg: "#fef3c7", fg: "#d97706" };
    case "positive": return { bg: "#d1fae5", fg: "#059669" };
    default:         return { bg: "#f1f5f9", fg: "#6b7280" };
  }
}

export function LiveVisualAnnotationsPage({
  liveVisualAnnotations,
}: {
  liveVisualAnnotations: LiveVisualAnnotations;
}) {
  const lva = liveVisualAnnotations;
  const agg = lva.aggregateInsights;
  const allAnnotations = lva.perPageAnnotations.flatMap((p) => p.annotations);
  const criticalCount = allAnnotations.filter((a) => a.severity === "critical").length;
  const highCount = allAnnotations.filter((a) => a.severity === "high").length;
  const moderateCount = allAnnotations.filter((a) => a.severity === "moderate").length;
  const positiveCount = allAnnotations.filter((a) => a.severity === "positive").length;

  const stats = [
    { label: "Critical", count: criticalCount, bg: "#fee2e2", fg: "#dc2626" },
    { label: "High", count: highCount, bg: "#ffedd5", fg: "#ea580c" },
    { label: "Moderate", count: moderateCount, bg: "#fef3c7", fg: "#d97706" },
    { label: "Positive", count: positiveCount, bg: "#d1fae5", fg: "#059669" },
  ];

  return (
    <View>
      <Text style={s.heading}>Live Site Visual Analysis</Text>
      <Text style={s.subheading}>
        {lva.perPageAnnotations.length} page{lva.perPageAnnotations.length !== 1 ? "s" : ""} captured · {agg.totalAnnotations} annotations · {new Date(lva.windowDate).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
      </Text>

      {/* Stats strip */}
      <View style={s.statsRow} wrap={false}>
        {stats.map((st) => (
          <View key={st.label} style={[s.statCard, { backgroundColor: st.bg }]}>
            <Text style={[s.statValue, { color: st.fg }]}>{st.count}</Text>
            <Text style={s.statLabel}>{st.label}</Text>
          </View>
        ))}
      </View>

      {/* Top priority annotations */}
      {agg.topPriorityAnnotations.length > 0 && (
        <View style={s.section}>
          <Text style={s.sectionHeading}>Top Priority Issues</Text>
          {agg.topPriorityAnnotations.slice(0, 5).map((ann, i) => {
            const { bg, fg } = severityColors(ann.severity);
            return (
              <View key={i} style={s.priorityCard} wrap={false}>
                <View style={s.badgeRow}>
                  <View style={[s.badge, { backgroundColor: bg }]}>
                    <Text style={[s.badgeText, { color: fg }]}>{ann.severity.toUpperCase()}</Text>
                  </View>
                  <Text style={s.cellMuted}>{ann.pageUrl.replace(/^https?:\/\//, "").slice(0, 50)}</Text>
                </View>
                <Text style={s.priorityLabel}>{ann.shortLabel}</Text>
                <Text style={s.priorityDesc}>{ann.description.slice(0, 160)}</Text>
              </View>
            );
          })}
        </View>
      )}

      {/* Per-page annotated screenshots */}
      {lva.perPageAnnotations.map((page, pi) => (
        <View key={pi} style={s.pageSection} break={pi > 0}>
          <View style={s.pageLabelRow}>
            <Text style={s.pageTypeLabel}>{page.pageLabel}</Text>
            <Text style={s.pageUrlText}>{page.pageUrl.replace(/^https?:\/\//, "").slice(0, 60)}</Text>
          </View>

          {/* Annotated screenshot */}
          <Image
            src={page.desktopAnnotatedScreenshotUrl}
            style={s.screenshot}
          />

          {/* Annotation table */}
          {page.annotations.length > 0 && (
            <View style={s.table}>
              <View style={s.headerRow}>
                <Text style={[s.colHeader, { width: 16 }]}>#</Text>
                <Text style={[s.colHeader, { width: 48 }]}>SEVERITY</Text>
                <Text style={[s.colHeader, { flex: 1.2 }]}>ISSUE</Text>
                <Text style={[s.colHeader, { flex: 2 }]}>DESCRIPTION</Text>
                <Text style={[s.colHeader, { flex: 1.5 }]}>ACTION</Text>
              </View>
              {page.annotations.map((ann, ai) => {
                const { bg, fg } = severityColors(ann.severity);
                return (
                  <View key={ai} style={[s.tableRow, ai % 2 === 1 ? s.rowAlt : {}]} wrap={false}>
                    <Text style={[s.cellText, { width: 16, color: ann.color }]}>{ann.number}</Text>
                    <View style={{ width: 48 }}>
                      <View style={[{ borderRadius: 2, paddingHorizontal: 3, paddingVertical: 1, backgroundColor: bg }]}>
                        <Text style={{ fontSize: 6, color: fg, fontFamily: "Helvetica-Bold" }}>{ann.severity}</Text>
                      </View>
                    </View>
                    <Text style={[s.cellText, { flex: 1.2 }]}>{ann.shortLabel}</Text>
                    <Text style={[s.cellMuted, { flex: 2 }]}>{ann.description.slice(0, 100)}</Text>
                    <Text style={[s.cellMuted, { flex: 1.5 }]}>{ann.linkedAction?.slice(0, 60) ?? "—"}</Text>
                  </View>
                );
              })}
            </View>
          )}
        </View>
      ))}

      <Text style={s.disclosureText}>{lva.patentRelevance}</Text>
    </View>
  );
}
