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

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 6 },
  lead: { ...S.body, lineHeight: 1.6, marginBottom: 16 },
  groupHeader: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
    marginBottom: 10,
    marginTop: 4,
  },
  groupTitle: { fontSize: 14, fontFamily: "Helvetica-Bold", color: C.ink },
  groupBadge: {
    backgroundColor: C.accentLight,
    borderRadius: 3,
    paddingHorizontal: 7,
    paddingVertical: 2,
  },
  groupBadgeText: { fontSize: 8.5, color: C.accent, fontFamily: "Helvetica-Bold" },
  actionCard: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 13,
    marginBottom: 10,
    backgroundColor: C.white,
  },
  actionTitle: { fontSize: 11, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 5 },
  urlsLabel: { ...S.label, marginBottom: 4 },
  urlText: { fontSize: 8.5, fontFamily: "Courier", color: C.accent, lineHeight: 1.6 },
  urlMore: { fontSize: 8, color: C.muted, marginBottom: 8 },
  codeBlock: {
    backgroundColor: "#f5f5f5",
    borderRadius: 4,
    padding: 10,
    marginTop: 6,
    marginBottom: 6,
  },
  codeLabel: { ...S.label, color: C.muted, marginBottom: 5 },
  codeText: {
    fontSize: 8,
    fontFamily: "Courier",
    color: "#1e293b",
    lineHeight: 1.65,
  },
  copyBlock: {
    marginTop: 8,
    paddingTop: 8,
    borderTopWidth: 0.5,
    borderTopColor: C.border,
  },
  copyLabel: { ...S.label, marginBottom: 4 },
  copyText: { fontSize: 9.5, color: C.body, fontFamily: "Helvetica-Oblique", lineHeight: 1.6 },
  stepsBlock: { marginTop: 8 },
  stepsLabel: { ...S.label, marginBottom: 5 },
  stepRow: { flexDirection: "row", marginBottom: 4 },
  stepNum: { width: 16, fontSize: 9, color: C.accent, fontFamily: "Helvetica-Bold" },
  stepText: { flex: 1, fontSize: 9, color: C.body, lineHeight: 1.5 },
  divider: { borderTopWidth: 0.75, borderTopColor: C.border, marginVertical: 14 },
});

const GROUP_ORDER = ["Schema", "Meta", "CTA", "Content", "Performance", "Redirect"] as const;

interface Props {
  seo: SeoSection;
}

export function ImplementationReferencePage({ seo }: Props) {
  const actionsWithImpl = (seo.priorityActions ?? []).filter(
    (a) => a.implementation?.codeSnippet || a.implementation?.copyRecommendation,
  );

  if (actionsWithImpl.length === 0) {
    if (typeof console !== "undefined") {
      // Synthesizer regression: no implementation data produced
      console.warn("[pdf] ImplementationReferencePage: no priority actions with implementation data — section omitted");
    }
    return null;
  }

  // Group by implementation type
  const groups = new Map<string, typeof actionsWithImpl>();
  for (const a of actionsWithImpl) {
    const type = a.implementation?.type ?? "Content";
    if (!groups.has(type)) groups.set(type, []);
    groups.get(type)!.push(a);
  }

  // Sort groups by canonical order
  const sortedGroups: Array<{ type: string; actions: typeof actionsWithImpl }> = GROUP_ORDER
    .filter((g) => groups.has(g))
    .map((g) => ({ type: g as string, actions: groups.get(g)! }));
  // Append any unknown types last
  const groupOrderSet = new Set<string>(GROUP_ORDER);
  for (const [type, actions] of groups) {
    if (!groupOrderSet.has(type)) {
      sortedGroups.push({ type, actions });
    }
  }

  return (
    <View>
      <Text style={s.heading}>Implementation Reference</Text>
      <Text style={s.lead}>
        Paste-ready code and copy for the priority actions in this report. Snippets are grouped by implementation type.
      </Text>

      {sortedGroups.map(({ type, actions }, groupIdx) => (
        <View key={type} break={groupIdx > 0}>
          <View style={s.groupHeader}>
            <Text style={s.groupTitle}>{type}</Text>
            <View style={s.groupBadge}>
              <Text style={s.groupBadgeText}>{actions.length} action{actions.length !== 1 ? "s" : ""}</Text>
            </View>
          </View>

          {actions.map((action, i) => {
            const impl = action.implementation!;
            const affectedUrls: string[] = [];
            return (
              <View key={i} style={s.actionCard} wrap>
                <Text style={s.actionTitle}>{action.title}</Text>

                {affectedUrls.length > 0 && (
                  <View>
                    <Text style={s.urlsLabel}>Target URLs</Text>
                    {affectedUrls.slice(0, 5).map((url, j) => (
                      <Text key={j} style={s.urlText}>{url}</Text>
                    ))}
                    {affectedUrls.length > 5 && (
                      <Text style={s.urlMore}>…and {affectedUrls.length - 5} more</Text>
                    )}
                  </View>
                )}

                {impl.codeSnippet && (
                  <View style={s.codeBlock} wrap>
                    <Text style={s.codeLabel}>Code snippet</Text>
                    <Text style={s.codeText}>{impl.codeSnippet}</Text>
                  </View>
                )}

                {impl.copyRecommendation && (
                  <View style={s.copyBlock}>
                    <Text style={s.copyLabel}>Recommended copy</Text>
                    <Text style={s.copyText}>{`"${impl.copyRecommendation}"`}</Text>
                  </View>
                )}

                {impl.implementationSteps && impl.implementationSteps.length > 0 && (
                  <View style={s.stepsBlock}>
                    <Text style={s.stepsLabel}>Steps</Text>
                    {impl.implementationSteps.map((step, j) => (
                      <View key={j} style={s.stepRow}>
                        <Text style={s.stepNum}>{j + 1}.</Text>
                        <Text style={s.stepText}>{step}</Text>
                      </View>
                    ))}
                  </View>
                )}
              </View>
            );
          })}

          {groupIdx < sortedGroups.length - 1 && <View style={s.divider} />}
        </View>
      ))}
    </View>
  );
}
