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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 4 },
  subheading: { ...S.small, marginBottom: 16, color: C.muted },
  // Confidence pill
  pill: { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 2, alignSelf: "flex-start", marginBottom: 14 },
  pillText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", letterSpacing: 0.8 },
  // Section wrapper
  section: { marginBottom: 16 },
  sectionHeading: { fontSize: 10, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 8 },
  // Page block
  pageBlock: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, marginBottom: 10, overflow: "hidden" },
  pageHeader: { backgroundColor: C.surface, paddingHorizontal: 10, paddingVertical: 6, borderBottomWidth: 0.75, borderBottomColor: C.border },
  pageUrl: { fontSize: 8.5, fontFamily: "Courier", color: C.ink },
  pageStats: { fontSize: 7, color: C.muted, marginTop: 1 },
  pageBody: { padding: 10 },
  // Heatmap grid (6 rows x 3 cols)
  gridContainer: { marginBottom: 8 },
  gridRow: { flexDirection: "row", gap: 1, marginBottom: 1 },
  gridCell: { flex: 1, height: 14, borderRadius: 2, alignItems: "center", justifyContent: "center" },
  gridCellText: { fontSize: 6, fontFamily: "Helvetica-Bold", color: "#ffffff" },
  gridCellTextDark: { fontSize: 6, fontFamily: "Helvetica-Bold", color: C.muted },
  gridLegend: { flexDirection: "row", gap: 12, marginTop: 4 },
  legendItem: { flexDirection: "row", alignItems: "center", gap: 3 },
  legendDot: { width: 6, height: 6, borderRadius: 3 },
  legendText: { fontSize: 6, color: C.muted },
  // Two-column layout for grid + elements
  twoCol: { flexDirection: "row", gap: 10, marginBottom: 8 },
  colLeft: { flex: 1 },
  colRight: { flex: 1 },
  subHeading: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, marginBottom: 4 },
  // Element row
  elemRow: { flexDirection: "row", alignItems: "center", gap: 4, marginBottom: 2 },
  elemLabel: { flex: 1, fontSize: 7.5, color: C.body },
  elemCount: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.ink },
  elemConv: { fontSize: 6.5, color: "#059669" },
  // Zone callouts
  zoneBlock: { borderRadius: 3, paddingHorizontal: 7, paddingVertical: 5, marginBottom: 5 },
  zoneTitle: { fontSize: 7.5, fontFamily: "Helvetica-Bold", marginBottom: 2 },
  zoneText: { fontSize: 7, lineHeight: 1.4 },
  // Table
  table: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, overflow: "hidden", marginBottom: 6 },
  headerRow: { flexDirection: "row", backgroundColor: C.surface, paddingHorizontal: 8, paddingVertical: 5, borderBottomWidth: 0.75, borderBottomColor: C.border },
  tableRow: { flexDirection: "row", paddingHorizontal: 8, paddingVertical: 4, borderBottomWidth: 0.5, borderBottomColor: "#f1f5f9" },
  rowAlt: { backgroundColor: "#fafafa" },
  colHeader: { fontSize: 7, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.6 },
  cellText: { fontSize: 8, color: C.body },
  cellMuted: { fontSize: 7, color: C.muted },
  // Insight block
  insightBlock: { borderWidth: 0.75, borderColor: C.border, borderRadius: 4, padding: 9, marginBottom: 8, backgroundColor: C.surface },
  insightText: { fontSize: 8.5, color: C.body, marginBottom: 3, lineHeight: 1.4 },
  insightPages: { fontSize: 7, color: C.muted, marginBottom: 2 },
  insightAction: { fontSize: 7.5, color: "#4f46e5" },
  // Patent
  patent: { fontSize: 7.5, color: C.muted, fontStyle: "italic" },
  // Placeholder
  placeholder: { borderWidth: 0.75, borderColor: "#fcd34d", borderRadius: 4, padding: 14, backgroundColor: "#fffbeb" },
  placeholderTitle: { fontSize: 10, fontFamily: "Helvetica-Bold", color: "#92400e", marginBottom: 8 },
  placeholderItem: { fontSize: 8, color: "#b45309", lineHeight: 1.5, marginBottom: 3 },
});

// ─── Grid colours ─────────────────────────────────────────────────────────────

function cellBg(sharePercent: number, hasConversionPath: boolean): string {
  if (sharePercent === 0) return "#f8fafc";
  if (hasConversionPath) {
    if (sharePercent >= 30) return "#10b981";
    if (sharePercent >= 15) return "#34d399";
    if (sharePercent >= 5) return "#6ee7b7";
    return "#d1fae5";
  }
  if (sharePercent >= 30) return "#f59e0b";
  if (sharePercent >= 15) return "#fbbf24";
  if (sharePercent >= 5) return "#fde68a";
  return "#fef3c7";
}

function cellTextDark(sharePercent: number): boolean {
  return sharePercent > 0 && sharePercent < 15;
}

const Y_LABELS = ["Header / Nav", "Hero Area", "Upper Content", "Mid Content", "Lower Content", "Footer"];

function buildGrid(
  regions: ConversionHeatMap["perPage"][number]["clickDensityRegions"],
): Array<Array<{ sharePercent: number; hasConversionPath: boolean }>> {
  const grid = Array.from({ length: 6 }, () =>
    Array.from({ length: 3 }, () => ({ sharePercent: 0, hasConversionPath: false })),
  );
  for (const r of regions) {
    const yIdx = Y_LABELS.findIndex((y) => r.regionLabel.startsWith(y));
    const xIdx = r.regionLabel.includes("(left)") ? 0 : r.regionLabel.includes("(right)") ? 2 : 1;
    if (yIdx >= 0) {
      grid[yIdx][xIdx] = { sharePercent: r.sharePercent, hasConversionPath: r.hasConversionPath };
    }
  }
  return grid;
}

function urlPath(url: string): string {
  try { return new URL(url).pathname || "/"; } catch { return url; }
}

// ─── Confidence pill ──────────────────────────────────────────────────────────

function ConfidencePill({ level }: { level: string }) {
  const cfg: Record<string, { label: string; bg: string; color: string }> = {
    high:         { label: "High confidence",    bg: "#d1fae5", color: "#065f46" },
    moderate:     { label: "Moderate confidence", bg: "#fef3c7", color: "#92400e" },
    low:          { label: "Limited data",        bg: C.surface, color: C.muted },
    insufficient: { label: "Insufficient data",   bg: C.surface, color: C.muted },
  };
  const c = cfg[level] ?? cfg.low;
  return (
    <View style={[s.pill, { backgroundColor: c.bg }]}>
      <Text style={[s.pillText, { color: c.color }]}>{c.label.toUpperCase()}</Text>
    </View>
  );
}

// ─── Page block ───────────────────────────────────────────────────────────────

function PageBlock({ page }: { page: ConversionHeatMap["perPage"][number] }) {
  const grid = buildGrid(page.clickDensityRegions);

  return (
    <View style={s.pageBlock} wrap={false}>
      <View style={s.pageHeader}>
        <Text style={s.pageUrl}>{urlPath(page.pageUrl)}</Text>
        <Text style={s.pageStats}>
          {page.totalClicks.toLocaleString()} clicks · {page.totalSessions.toLocaleString()} sessions · {page.clicksPerSession} clicks/session · {page.pageType}
        </Text>
      </View>
      <View style={s.pageBody}>
        {/* Two-column: grid + elements */}
        <View style={s.twoCol}>
          {/* Region heatmap grid */}
          <View style={s.colLeft}>
            <Text style={s.subHeading}>CLICK DENSITY MAP</Text>
            <View style={s.gridContainer}>
              {grid.map((row, yIdx) => (
                <View key={yIdx} style={s.gridRow}>
                  {row.map((cell, xIdx) => (
                    <View
                      key={xIdx}
                      style={[s.gridCell, { backgroundColor: cellBg(cell.sharePercent, cell.hasConversionPath) }]}
                    >
                      {cell.sharePercent > 0 && (
                        <Text style={cellTextDark(cell.sharePercent) ? s.gridCellTextDark : s.gridCellText}>
                          {cell.sharePercent}%
                        </Text>
                      )}
                    </View>
                  ))}
                </View>
              ))}
            </View>
            <View style={s.gridLegend}>
              <View style={s.legendItem}>
                <View style={[s.legendDot, { backgroundColor: "#10b981" }]} />
                <Text style={s.legendText}>Conversion path</Text>
              </View>
              <View style={s.legendItem}>
                <View style={[s.legendDot, { backgroundColor: "#f59e0b" }]} />
                <Text style={s.legendText}>High engagement</Text>
              </View>
            </View>
          </View>

          {/* Top elements */}
          <View style={s.colRight}>
            <Text style={s.subHeading}>TOP CLICKED ELEMENTS</Text>
            {page.topClickedElements.slice(0, 6).map((el, i) => (
              <View key={i} style={s.elemRow}>
                <Text style={[s.elemCount, { width: 14 }]}>{i + 1}.</Text>
                <Text style={s.elemLabel}>{el.elementLabel.slice(0, 40)}</Text>
                <Text style={s.elemCount}>{el.clickCount}</Text>
                {el.conversionContribution > 0 && (
                  <Text style={s.elemConv}>{el.conversionContributionPercent}%</Text>
                )}
              </View>
            ))}
          </View>
        </View>

        {/* Dead zones */}
        {page.deadZones.slice(0, 2).map((z, i) => (
          <View key={i} style={[s.zoneBlock, { backgroundColor: "#fef2f2", borderWidth: 0.5, borderColor: "#fecaca" }]}>
            <Text style={[s.zoneTitle, { color: "#dc2626" }]}>Dead Zone: {z.regionLabel} ({z.missedClickRatio}:1 view-to-click)</Text>
            <Text style={[s.zoneText, { color: "#b91c1c" }]}>{z.recommendation}</Text>
          </View>
        ))}

        {/* Hot zones */}
        {page.hotZones.slice(0, 2).map((z, i) => (
          <View key={i} style={[s.zoneBlock, { backgroundColor: "#f0fdf4", borderWidth: 0.5, borderColor: "#bbf7d0" }]}>
            <Text style={[s.zoneTitle, { color: "#15803d" }]}>Hot Zone: {z.regionLabel} ({z.clickCount.toLocaleString()} clicks)</Text>
            <Text style={[s.zoneText, { color: "#166534" }]}>{z.recommendation}</Text>
          </View>
        ))}

        {/* Recommended CTA placements */}
        {page.recommendedCtaPlacements.slice(0, 2).map((r, i) => (
          <View key={i} style={[s.zoneBlock, { backgroundColor: "#fffbeb", borderWidth: 0.5, borderColor: "#fde68a" }]}>
            <Text style={[s.zoneTitle, { color: "#92400e" }]}>Recommended CTA: {r.regionLabel}</Text>
            <Text style={[s.zoneText, { color: "#b45309" }]}>{r.rationale}</Text>
            <Text style={[s.zoneText, { color: "#d97706", fontStyle: "italic" }]}>{r.expectedLift}</Text>
          </View>
        ))}
      </View>
    </View>
  );
}

// ─── Placeholder ──────────────────────────────────────────────────────────────

function PlaceholderContent() {
  return (
    <View style={s.placeholder}>
      <Text style={s.placeholderTitle}>Click Event Capture Not Detected</Text>
      <Text style={s.placeholderItem}>• Click capture requires Site Tag v2 or later with the heatmap module enabled</Text>
      <Text style={s.placeholderItem}>• Enables: click density heatmaps, CTA placement recommendations, dead zone detection</Text>
      <Text style={s.placeholderItem}>• Action: confirm Site Tag installation includes click capture configuration</Text>
    </View>
  );
}

// ─── Main export ──────────────────────────────────────────────────────────────

export function ConversionHeatMapPage({
  conversionHeatMap: chm,
}: {
  conversionHeatMap: ConversionHeatMap;
}) {
  return (
    <>
      <Text style={s.heading}>Conversion Heat Map</Text>
      <Text style={s.subheading}>
        Where visitors actually click vs where CTAs exist — last {chm.windowDays} days
      </Text>

      {!chm.hasClickData ? (
        <PlaceholderContent />
      ) : (
        <>
          <ConfidencePill level={chm.dataConfidence} />

          {/* Per-page blocks */}
          {chm.perPage.length > 0 && (
            <View style={s.section}>
              <Text style={s.sectionHeading}>Page-Level Click Analysis</Text>
              {chm.perPage.map((page) => (
                <PageBlock key={page.pageUrl} page={page} />
              ))}
            </View>
          )}

          {/* Aggregate insights */}
          {chm.aggregateInsights.length > 0 && (
            <View style={s.section}>
              <Text style={s.sectionHeading}>Cross-Page Patterns</Text>
              {chm.aggregateInsights.map((ins, i) => (
                <View key={i} style={s.insightBlock} wrap={false}>
                  <Text style={s.insightText}>{ins.insight}</Text>
                  {ins.affectedPages.length > 0 && (
                    <Text style={s.insightPages}>
                      Affected: {ins.affectedPages.slice(0, 4).join(", ")}
                      {ins.affectedPages.length > 4 ? ` +${ins.affectedPages.length - 4} more` : ""}
                    </Text>
                  )}
                  <Text style={s.insightAction}>{ins.actionRecommendation}</Text>
                </View>
              ))}
            </View>
          )}

          <Text style={s.patent}>{chm.patentRelevance}</Text>
        </>
      )}
    </>
  );
}
