import type {
  Announcement,
  AnnouncementDisplayState,
  AnnouncementFieldErrors,
  AnnouncementFormat,
  AnnouncementInput,
  AnnouncementStep,
  LocalizedText,
} from "@/domain/entities/announcement";
import {
  ANNOUNCEMENT_LIMITS,
  DEFAULT_AUDIENCE,
  DEFAULT_NOTIFY,
  DEFAULT_REMINDER,
  DEFAULT_RULES,
  FORMAT_FIELDS,
  STEP_PLACEMENTS,
} from "@/shared/constants/announcements";

// ── Display state (spec §6.1) ────────────────────────────────────────────────

/** "Programmée / En ligne / Terminée" come from the dates; only draft/published/archived are stored. */
export function displayState(
  a: Pick<Announcement, "status" | "starts_at" | "ends_at">,
  now: number = Date.now(),
): AnnouncementDisplayState {
  if (a.status === "draft") return "draft";
  if (a.status === "archived") return "archived";
  if (a.starts_at && new Date(a.starts_at).getTime() > now) return "scheduled";
  if (a.ends_at && new Date(a.ends_at).getTime() < now) return "ended";
  return "live";
}

// ── Menu anchors ─────────────────────────────────────────────────────────────

/** A menu group of Fleet (a sidebar section of several entries), by its section id. */
export const MENU_GROUP_PREFIX = "sidebar-group.";

export const isMenuGroup = (key?: string | null): boolean => (key ?? "").startsWith(MENU_GROUP_PREFIX);

/** In Fleet's menu: an entry ("sidebar.<page key>") or a group. Both are offered on every page. */
export const isMenuAnchor = (key?: string | null): boolean => (key ?? "").startsWith("sidebar.") || isMenuGroup(key);

// ── Small helpers ────────────────────────────────────────────────────────────

/** True when the instant is still to come. */
export function isFuture(iso: string | null): boolean {
  return !!iso && new Date(iso).getTime() > Date.now();
}

export const emptyText = (): LocalizedText => ({ fr: "", en: "" });

export function slugify(value: string): string {
  return value
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 60);
}

export const KEY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

/** Links may only point inside Fleet: "/fleet/..." with no scheme, host or "..". */
export function isInternalPath(path: string): boolean {
  return /^\/fleet(\/[A-Za-z0-9\-._~%!$&'()*+,;=:@?#/]*)?$/.test(path) && !path.includes("//") && !path.includes("..");
}

let stepSeq = 0;
export function newStepId(): string {
  stepSeq += 1;
  return `new-${Date.now().toString(36)}-${stepSeq}`;
}

export function newStep(): AnnouncementStep {
  return {
    id: newStepId(),
    title: emptyText(),
    subtitle: emptyText(),
    body: emptyText(),
    icon: null,
    media_url: null,
    media_alt: emptyText(),
    anchor_key: null,
    placement: "auto",
    cta_label: emptyText(),
    cta_path: null,
  };
}

export function emptyInput(format: AnnouncementFormat = "banner"): AnnouncementInput {
  const spec = FORMAT_FIELDS[format];
  return {
    key: "",
    format,
    title: emptyText(),
    body: emptyText(),
    badge_text: { fr: "Nouveau", en: "New" },
    category: null,
    icon: "Sparkles",
    media_url: null,
    media_alt: emptyText(),
    cta_label: emptyText(),
    cta_path: null,
    page_key: null,
    target_sidebar_path: null,
    anchor_key: null,
    placement: spec.placements[0] ?? "auto",
    widget_corner: "bottom_right",
    steps: spec.steps ? Array.from({ length: spec.steps.min }, newStep) : [],
    audience: { ...DEFAULT_AUDIENCE },
    starts_at: null,
    ends_at: null,
    priority: 5,
    rules: { ...DEFAULT_RULES },
    success_event: null,
    reminder: { ...DEFAULT_REMINDER },
    notify: { ...DEFAULT_NOTIFY, message: emptyText() },
  };
}

export function toInput(a: Announcement): AnnouncementInput {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { id, status, round, first_published_at, counts, created_by, updated_at, created_at, ...input } = a;
  return structuredClone(input);
}

/**
 * Switching format keeps what still applies and clears the rest (spec §4.4).
 * Steps are kept up to the new maximum and padded to the new minimum.
 */
export function applyFormatChange(input: AnnouncementInput, format: AnnouncementFormat): AnnouncementInput {
  const spec = FORMAT_FIELDS[format];
  const next: AnnouncementInput = { ...input, format };

  if (spec.page === "none") next.page_key = null;
  if (spec.page === "required" && !next.page_key) next.page_key = null;
  if (spec.element === "none") {
    next.anchor_key = null;
    next.target_sidebar_path = null;
  }
  if (spec.element === "menu" && next.anchor_key && !isMenuAnchor(next.anchor_key)) next.anchor_key = null;
  if (spec.placements.length === 0) next.placement = "auto";
  else if (!spec.placements.includes(next.placement)) next.placement = spec.placements[0];
  if (spec.bodyMax === 0) next.body = emptyText();
  if (!spec.image) {
    next.media_url = null;
    next.media_alt = emptyText();
  }
  if (!spec.cta) {
    next.cta_label = emptyText();
    next.cta_path = null;
  }

  if (!spec.steps) {
    next.steps = [];
  } else {
    let steps = input.steps.slice(0, spec.steps.max);
    while (steps.length < spec.steps.min) steps = [...steps, newStep()];
    next.steps = steps.map((s) => ({
      ...s,
      placement: STEP_PLACEMENTS.includes(s.placement) ? s.placement : "auto",
    }));
  }
  return next;
}

// ── Restricted rich text (spec §5: bold, italic, line break, internal link) ─

const ALLOWED_TAGS = new Set(["B", "STRONG", "I", "EM", "A", "BR"]);

/** Keeps <b>, <i>, <br> and internal <a href="/fleet/...">; everything else is unwrapped. */
export function sanitizeRichText(html: string): string {
  if (!html) return "";
  if (typeof DOMParser === "undefined") return html.replace(/<(?!\/?(b|i|br|a)(\s|>|\/))[^>]*>/gi, "");

  const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
  const root = doc.body.firstElementChild as HTMLElement;

  const clean = (node: Node): Node[] => {
    if (node.nodeType === Node.TEXT_NODE) return [doc.createTextNode(node.textContent ?? "")];
    if (node.nodeType !== Node.ELEMENT_NODE) return [];
    const el = node as HTMLElement;
    const children = Array.from(el.childNodes).flatMap(clean);
    // Blocks the browser inserts on Enter become line breaks.
    if (el.tagName === "DIV" || el.tagName === "P") return [...children, doc.createElement("br")];
    if (!ALLOWED_TAGS.has(el.tagName)) return children;
    const tag = el.tagName === "STRONG" ? "b" : el.tagName === "EM" ? "i" : el.tagName.toLowerCase();
    const out = doc.createElement(tag);
    if (tag === "a") {
      const href = el.getAttribute("href") ?? "";
      if (!isInternalPath(href)) return children;
      out.setAttribute("href", href);
    }
    children.forEach((c) => out.appendChild(c));
    return [out];
  };

  const wrapper = doc.createElement("div");
  Array.from(root.childNodes).flatMap(clean).forEach((n) => wrapper.appendChild(n));
  return wrapper.innerHTML.replace(/(<br>)+$/, "");
}

/** Visible characters of a rich text (what the length limits count). */
export function plainText(html: string): string {
  return html
    .replace(/<br\s*\/?>/gi, "\n")
    .replace(/<[^>]*>/g, "")
    .replace(/&nbsp;/g, " ")
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'");
}

// ── Validation (spec §5, §6.4) ───────────────────────────────────────────────

export type ValidationCode =
  | "required"
  | "tooLong"
  | "internalPath"
  | "altRequired"
  | "stepsMin"
  | "stepsMax"
  | "stepAnchorRequired"
  | "pageRequired"
  | "elementRequired"
  | "menuRequired"
  | "endBeforeStart"
  | "audienceEmpty"
  | "keyFormat"
  | "keyTaken"
  | "ctaIncomplete"
  | "notifyMessage";

export interface ValidationIssue {
  field: string;
  code: ValidationCode;
  max?: number;
  min?: number;
}

/**
 * The checks the backend runs (422). "draft" only refuses what can never be saved
 * (bad key, over-long text, external link); "publish" also requires what Fleet needs to show it.
 */
export function validateAnnouncement(input: AnnouncementInput, mode: "draft" | "publish"): ValidationIssue[] {
  const issues: ValidationIssue[] = [];
  const spec = FORMAT_FIELDS[input.format];
  const push = (field: string, code: ValidationCode, extra: Partial<ValidationIssue> = {}) =>
    issues.push({ field, code, ...extra });
  const len = (v: string) => plainText(v).length;

  const checkText = (field: string, text: LocalizedText, max: number, required: boolean) => {
    if (required && !plainText(text.fr).trim()) push(`${field}.fr`, "required");
    (["fr", "en"] as const).forEach((lang) => {
      if (len(text[lang]) > max) push(`${field}.${lang}`, "tooLong", { max });
    });
  };

  const checkCta = (field: string, label: LocalizedText, path: string | null) => {
    checkText(`${field}_label`, label, ANNOUNCEMENT_LIMITS.ctaLabel, false);
    if (path && !isInternalPath(path)) push(`${field}_path`, "internalPath");
    if (mode === "publish" && !!path !== !!label.fr.trim()) push(`${field}_path`, "ctaIncomplete");
  };

  const checkMedia = (field: string, url: string | null, alt: LocalizedText) => {
    if (url && mode === "publish" && !alt.fr.trim()) push(`${field}_alt.fr`, "altRequired");
  };

  // Key
  if (!input.key) push("key", "required");
  else if (!KEY_PATTERN.test(input.key)) push("key", "keyFormat");

  checkText("title", input.title, ANNOUNCEMENT_LIMITS.title, true);
  if (spec.bodyMax > 0) checkText("body", input.body, spec.bodyMax, mode === "publish" && input.format !== "badge");
  if (spec.badgeText) checkText("badge_text", input.badge_text, ANNOUNCEMENT_LIMITS.badgeText, input.format === "badge" && mode === "publish");
  if (spec.cta) checkCta("cta", input.cta_label, input.cta_path);
  if (spec.image) checkMedia("media", input.media_url, input.media_alt);

  if (mode === "publish") {
    if (spec.page === "required" && !input.page_key) push("page_key", "pageRequired");
    if (spec.element === "any" && !input.anchor_key) push("anchor_key", "elementRequired");
    if (spec.element === "menu" && !input.anchor_key) push("anchor_key", "menuRequired");
  }

  if (spec.steps) {
    if (input.steps.length < spec.steps.min) push("steps", "stepsMin", { min: spec.steps.min });
    if (input.steps.length > spec.steps.max) push("steps", "stepsMax", { max: spec.steps.max });
    input.steps.forEach((step, i) => {
      const f = `steps.${i}`;
      checkText(`${f}.title`, step.title, ANNOUNCEMENT_LIMITS.stepTitle, mode === "publish");
      checkText(`${f}.subtitle`, step.subtitle, ANNOUNCEMENT_LIMITS.stepSubtitle, false);
      checkText(`${f}.body`, step.body, ANNOUNCEMENT_LIMITS.stepBody, mode === "publish");
      checkCta(`${f}.cta`, step.cta_label, step.cta_path);
      checkMedia(`${f}.media`, step.media_url, step.media_alt);
      if (mode === "publish" && spec.steps!.anchor === "required" && !step.anchor_key) push(`${f}.anchor_key`, "stepAnchorRequired");
    });
  }

  if (input.starts_at && input.ends_at && new Date(input.ends_at) <= new Date(input.starts_at)) {
    push("ends_at", "endBeforeStart");
  }

  if (mode === "publish") {
    const a = input.audience;
    const empty =
      !a.plans.length && !a.capabilities_required.length && !a.capabilities_missing.length &&
      !a.permissions.length && !a.roles.length && !a.companies_include.length && !a.languages.length &&
      !a.new_users_only;
    if (empty && !a.everyone_confirmed) push("audience", "audienceEmpty");
    if (input.notify.enabled && !input.notify.message.fr.trim()) push("notify.message.fr", "notifyMessage");
  }

  return issues;
}

/** Issues → the 422 `errors` shape, with a message per issue. */
export function issuesToFieldErrors(
  issues: ValidationIssue[],
  message: (issue: ValidationIssue) => string,
): AnnouncementFieldErrors {
  const errors: AnnouncementFieldErrors = {};
  for (const issue of issues) (errors[issue.field] ??= []).push(message(issue));
  return errors;
}

/** Field errors of an API failure (422), or null. */
export function extractFieldErrors(err: unknown): AnnouncementFieldErrors | null {
  const response = (err as { response?: { status?: number; data?: { errors?: AnnouncementFieldErrors } } })?.response;
  return response?.status === 422 && response.data?.errors ? response.data.errors : null;
}

// ── Europe/Paris dates (spec §6.5) ───────────────────────────────────────────

const PARIS = "Europe/Paris";

const parisParts = new Intl.DateTimeFormat("en-GB", {
  timeZone: PARIS,
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
  hourCycle: "h23",
});

function partsOf(date: Date) {
  const p = Object.fromEntries(parisParts.formatToParts(date).map((x) => [x.type, x.value]));
  return { y: +p.year, m: +p.month, d: +p.day, h: +p.hour, mi: +p.minute, s: +p.second };
}

/** Minutes Paris is ahead of UTC at this instant (+60 in winter, +120 in summer). */
function parisOffset(date: Date): number {
  const p = partsOf(date);
  return Math.round((Date.UTC(p.y, p.m - 1, p.d, p.h, p.mi, p.s) - date.getTime()) / 60000);
}

const pad = (n: number) => String(n).padStart(2, "0");

/** ISO instant → "YYYY-MM-DDTHH:mm" in Paris time, for a datetime-local input. */
export function toParisInput(iso: string | null): string {
  if (!iso) return "";
  const p = partsOf(new Date(iso));
  return `${p.y}-${pad(p.m)}-${pad(p.d)}T${pad(p.h)}:${pad(p.mi)}`;
}

/** "YYYY-MM-DDTHH:mm" read as Paris time → ISO 8601 with the Paris offset. */
export function fromParisInput(value: string): string | null {
  const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(value);
  if (!match) return null;
  const [y, m, d, h, mi] = match.slice(1).map(Number);
  const wall = Date.UTC(y, m - 1, d, h, mi);
  let offset = parisOffset(new Date(wall));
  offset = parisOffset(new Date(wall - offset * 60000));
  const sign = offset >= 0 ? "+" : "-";
  const abs = Math.abs(offset);
  return `${value}:00${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
}

/** A date shown in Paris time whatever the browser's time zone. */
export function formatParis(iso: string | null, locale: "fr" | "en", withTime = true): string {
  if (!iso) return "—";
  return new Date(iso).toLocaleString(locale === "fr" ? "fr-FR" : "en-GB", {
    timeZone: PARIS,
    day: "2-digit",
    month: "short",
    year: "numeric",
    ...(withTime ? { hour: "2-digit", minute: "2-digit" } : {}),
  });
}
