import { Node, mergeAttributes, ReactNodeViewRenderer } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
import { ImageBlockView } from "./image-block-view";

export interface ImageBlockOptions {
  parentNoteId: string;
}

export const ImageBlock = Node.create<ImageBlockOptions>({
  name: "noteImage",
  group: "block",
  atom: true,
  draggable: true,

  addOptions() {
    return {
      parentNoteId: "",
    };
  },

  addAttributes() {
    return {
      src: { default: null },
      alt: { default: "" },
      attachmentId: { default: null },
      // Width as a percentage of the editor column (20–100). Lets users
      // drag-resize the image instead of it always filling the width.
      width: { default: 100 },
      // "cover" crops to fill the frame, "contain" shows the whole image
      // letterboxed — exposed as a quick "change format" toggle.
      fit: { default: "cover" },
    };
  },

  parseHTML() {
    return [
      {
        tag: 'img[data-type="note-image"]',
        getAttrs: (element) => ({
          src: (element as HTMLElement).getAttribute("src"),
          alt: (element as HTMLElement).getAttribute("alt"),
        }),
      },
    ];
  },

  renderHTML({ HTMLAttributes, node }) {
    return [
      "img",
      mergeAttributes(HTMLAttributes, {
        src: node.attrs.src,
        alt: node.attrs.alt,
        "data-type": "note-image",
      }),
    ];
  },

  addNodeView() {
    return ReactNodeViewRenderer((props: NodeViewProps) => (
      <ImageBlockView {...props} options={this.options} />
    ));
  },
});
