import { mergeAttributes, Node } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";

import { FigureImageView } from "./figure-image-view";

export type ImageAlign = "left" | "center" | "right" | "full";

export type FigureImageAttributes = {
  src: string;
  alt: string;
  title: string;
  caption: string;
  align: ImageAlign;
  /** Width as a percentage of the text column, or null for the image's natural size. */
  width: number | null;
  naturalWidth: number | null;
  naturalHeight: number | null;
};

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    figureImage: {
      insertFigureImage: (
        attributes: Partial<FigureImageAttributes> & { src: string },
        position?: number,
      ) => ReturnType;
    };
  }
}

const ALIGNMENTS: ImageAlign[] = ["left", "center", "right", "full"];

const numberOrNull = (value: string | null | undefined) => {
  const number = Number.parseFloat(value ?? "");
  return Number.isFinite(number) && number > 0 ? number : null;
};

/**
 * Block image stored as
 * `<figure data-align style="width: N%"><img …><figcaption>…</figcaption></figure>`,
 * the markup the sanitizer and the website both expect. Only http(s) and
 * uploaded URLs are accepted; pasted data: URIs are dropped, so articles never
 * embed base64 images.
 */
export const FigureImage = Node.create({
  name: "image",
  group: "block",
  atom: true,
  draggable: true,
  selectable: true,

  addAttributes() {
    return {
      src: { default: "" },
      alt: { default: "" },
      title: { default: "" },
      caption: { default: "" },
      align: { default: "center" },
      width: { default: null },
      naturalWidth: { default: null },
      naturalHeight: { default: null },
    };
  },

  parseHTML() {
    const isAllowedSrc = (src: string | null) =>
      Boolean(src && (/^https?:\/\//i.test(src) || src.startsWith("/")));

    return [
      {
        tag: "figure",
        getAttrs: (element) => {
          const img = element.querySelector("img");
          const src = img?.getAttribute("src") ?? null;
          if (!img || !isAllowedSrc(src)) return false;
          const align = element.getAttribute("data-align") as ImageAlign | null;
          return {
            src,
            alt: img.getAttribute("alt") ?? "",
            title: img.getAttribute("title") ?? "",
            caption: element.querySelector("figcaption")?.textContent?.trim() ?? "",
            align: align && ALIGNMENTS.includes(align) ? align : "center",
            width: numberOrNull(element.style.width?.replace("%", "")),
            naturalWidth: numberOrNull(img.getAttribute("width")),
            naturalHeight: numberOrNull(img.getAttribute("height")),
          };
        },
      },
      {
        tag: "img[src]",
        getAttrs: (element) => {
          const src = element.getAttribute("src");
          if (!isAllowedSrc(src)) return false;
          return {
            src,
            alt: element.getAttribute("alt") ?? "",
            title: element.getAttribute("title") ?? "",
            naturalWidth: numberOrNull(element.getAttribute("width")),
            naturalHeight: numberOrNull(element.getAttribute("height")),
          };
        },
      },
    ];
  },

  renderHTML({ node }) {
    const attrs = node.attrs as FigureImageAttributes;
    const figureAttrs: Record<string, string> = { "data-align": attrs.align };
    if (attrs.width && attrs.align !== "full") {
      figureAttrs.style = `width: ${Math.round(attrs.width)}%`;
    }
    const img = [
      "img",
      mergeAttributes({
        src: attrs.src,
        alt: attrs.alt,
        ...(attrs.title && { title: attrs.title }),
        ...(attrs.naturalWidth && { width: attrs.naturalWidth }),
        ...(attrs.naturalHeight && { height: attrs.naturalHeight }),
      }),
    ] as const;

    return attrs.caption
      ? ["figure", figureAttrs, img, ["figcaption", {}, attrs.caption]]
      : ["figure", figureAttrs, img];
  },

  addCommands() {
    return {
      insertFigureImage:
        (attributes, position) =>
        ({ commands }) => {
          const content = { type: this.name, attrs: attributes };
          return position === undefined
            ? commands.insertContent(content)
            : commands.insertContentAt(position, content);
        },
    };
  },

  addNodeView() {
    return ReactNodeViewRenderer(FigureImageView);
  },
});
