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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 6 },
  subtext: { ...S.small, marginBottom: 14 },
  findingCard: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 13,
    marginBottom: 9,
    backgroundColor: C.white,
  },
  priorityBadge: {
    fontSize: 7,
    fontFamily: "Helvetica-Bold",
    letterSpacing: 1,
    textTransform: "uppercase",
    paddingHorizontal: 6,
    paddingVertical: 2.5,
    borderRadius: 3,
    alignSelf: "flex-start",
    marginBottom: 6,
  },
  findingTitle: { ...S.h3, marginBottom: 5 },
  findingDetail: { ...S.body, lineHeight: 1.6 },
  // Behavioral overlay
  overlayBar: {
    flexDirection: "row",
    gap: 14,
    marginTop: 10,
    paddingTop: 8,
    borderTopWidth: 0.5,
    borderTopColor: C.border,
  },
  overlayMetric: { alignItems: "flex-start" },
  overlayLabel: { ...S.caption, marginBottom: 1.5 },
  overlayValue: { fontSize: 13, fontFamily: "Helvetica-Bold", color: C.ink, lineHeight: 1 },
  overlayValueAccent: { fontSize: 13, fontFamily: "Helvetica-Bold", color: C.amber, lineHeight: 1 },
  // Recommended steps
  stepsBlock: { marginTop: 8 },
  stepsLabel: { ...S.label, marginBottom: 4 },
  stepRow: { flexDirection: "row", marginBottom: 4 },
  stepBullet: { width: 14, fontSize: 9.5, color: C.accent, fontFamily: "Helvetica-Bold" },
  stepText: { flex: 1, fontSize: 9.5, color: C.body, lineHeight: 1.5 },
  // Affected URLs
  urlBlock: { marginTop: 8, paddingTop: 7, borderTopWidth: 0.5, borderTopColor: C.border },
  urlsLabel: { ...S.label, marginBottom: 3 },
  urlText: { fontSize: 8.5, color: C.accent, fontFamily: "Helvetica", lineHeight: 1.5 },
  urlMore: { fontSize: 8, color: C.muted, marginTop: 1 },
});

function priorityStyle(priority: string) {
  switch (priority?.toLowerCase()) {
    case "critical": return { bg: "#fef2f2", text: C.red, border: "#fecaca" };
    case "high": return { bg: "#fff7ed", text: "#c2410c", border: "#fed7aa" };
    case "medium": case "moderate": return { bg: "#fffbeb", text: C.amber, border: "#fde68a" };
    default: return { bg: C.surface, text: C.muted, border: C.border };
  }
}

function fmtDuration(s: number): string {
  if (s < 60) return `${Math.round(s)}s`;
  const m = Math.floor(s / 60);
  const sec = Math.round(s % 60);
  return sec > 0 ? `${m}m ${sec}s` : `${m}m`;
}

function BehavioralBar({ overlay }: { overlay: BehavioralOverlay }) {
  const items: Array<{ label: string; value: string; accent?: boolean }> = [];
  if (overlay.bounceRate != null)
    items.push({ label: "Bounce Rate", value: `${(overlay.bounceRate * 100).toFixed(0)}%` });
  if (overlay.avgSessionDuration != null)
    items.push({ label: "Avg Session", value: fmtDuration(overlay.avgSessionDuration) });
  if (overlay.conversions > 0)
    items.push({ label: "Conversions", value: String(overlay.conversions) });
  if (overlay.estimatedLostConversionValue > 0)
    items.push({ label: "Est. Lost Value", value: `$${overlay.estimatedLostConversionValue.toFixed(0)}`, accent: true });
  if (items.length === 0) return null;
  return (
    <View style={s.overlayBar}>
      {items.map(({ label, value, accent }) => (
        <View key={label} style={s.overlayMetric}>
          <Text style={s.overlayLabel}>{label}</Text>
          <Text style={accent ? s.overlayValueAccent : s.overlayValue}>{value}</Text>
        </View>
      ))}
    </View>
  );
}

interface Props {
  seo: SeoSection;
}

export function KeyFindings({ seo }: Props) {
  const useDetailed = seo.prioritizedFindings && seo.prioritizedFindings.length > 0;

  return (
    <View>
      <Text style={s.heading}>Key Findings</Text>
      <Text style={s.subtext}>Prioritized by business impact. Highest-priority issues appear first.</Text>

      {useDetailed
        ? seo.prioritizedFindings!.slice(0, 10).map((f, i) => {
            const ps = priorityStyle(f.priority);
            return (
              <View key={i} style={{ flexDirection: "row", marginBottom: 9 }} wrap={false}>
                <View style={{ width: 4, backgroundColor: ps.text, borderRadius: 2, marginRight: 0 }} />
                <View style={[s.findingCard, { flex: 1, marginBottom: 0, borderLeftWidth: 0, borderTopLeftRadius: 0, borderBottomLeftRadius: 0 }]}>
                <View style={[s.priorityBadge, { backgroundColor: ps.bg, borderWidth: 0.5, borderColor: ps.border }]}>
                  <Text style={{ color: ps.text, fontSize: 7, fontFamily: "Helvetica-Bold", letterSpacing: 1 }}>
                    {f.priority.toUpperCase()}
                  </Text>
                </View>
                <Text style={s.findingTitle}>{f.title}</Text>
                {f.whatsWorking && (
                  <Text style={[s.findingDetail, { marginBottom: 4 }]}>
                    <Text style={{ fontFamily: "Helvetica-Bold", color: C.green }}>Working: </Text>
                    {f.whatsWorking}
                  </Text>
                )}
                <Text style={s.findingDetail}>
                  <Text style={{ fontFamily: "Helvetica-Bold", color: C.red }}>Gap: </Text>
                  {f.whereItFallsShort}
                </Text>
                {f.recommendedNextSteps && f.recommendedNextSteps.length > 0 && (
                  <View style={s.stepsBlock}>
                    <Text style={s.stepsLabel}>Next Steps</Text>
                    {f.recommendedNextSteps.slice(0, 3).map((step, j) => (
                      <View key={j} style={s.stepRow}>
                        <Text style={s.stepBullet}>{j + 1}.</Text>
                        <Text style={s.stepText}>{step}</Text>
                      </View>
                    ))}
                  </View>
                )}
                {f.affectedUrls && f.affectedUrls.length > 0 && (
                  <View style={s.urlBlock}>
                    <Text style={s.urlsLabel}>Affected URLs</Text>
                    {f.affectedUrls.slice(0, 5).map((url, j) => (
                      <Text key={j} style={s.urlText}>{url}</Text>
                    ))}
                    {f.affectedUrls.length > 5 && (
                      <Text style={s.urlMore}>...and {f.affectedUrls.length - 5} more</Text>
                    )}
                  </View>
                )}
                </View>
              </View>
            );
          })
        : seo.keyFindings.map((f, i) => (
            <View key={i} style={s.findingCard} wrap={false}>
              <Text style={s.findingTitle}>{f.title}</Text>
              <Text style={s.findingDetail}>{f.detail}</Text>
              {f.behavioralOverlay && <BehavioralBar overlay={f.behavioralOverlay} />}
            </View>
          ))}
    </View>
  );
}
