import { Extension } from "@tiptap/core";
import { Fragment } from "@tiptap/pm/model";
import { NodeSelection, TextSelection, type EditorState, type Transaction } from "@tiptap/pm/state";

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    moveBlock: {
      /** Moves the top-level block containing the selection one position up or down. */
      moveBlock: (direction: "up" | "down") => ReturnType;
    };
  }
}

function moveTopLevelBlock(
  state: EditorState,
  direction: "up" | "down",
  dispatch?: (tr: Transaction) => void,
) {
  const { selection, doc } = state;
  const index = selection.$from.index(0);
  const targetIndex = direction === "up" ? index - 1 : index + 1;
  if (index >= doc.childCount || targetIndex < 0 || targetIndex >= doc.childCount) {
    return false;
  }
  if (!dispatch) return true;

  const blockStart = (childIndex: number) => {
    let pos = 0;
    for (let i = 0; i < childIndex; i++) pos += doc.child(i).nodeSize;
    return pos;
  };

  const block = doc.child(index);
  const neighbour = doc.child(targetIndex);
  const start = blockStart(Math.min(index, targetIndex));
  const end = start + block.nodeSize + neighbour.nodeSize;
  const oldBlockStart = blockStart(index);
  const newBlockStart = direction === "up" ? start : start + neighbour.nodeSize;

  const tr = state.tr.replaceWith(
    start,
    end,
    Fragment.from(direction === "up" ? [block, neighbour] : [neighbour, block]),
  );

  // Keep the cursor (or node selection) on the moved block.
  const shift = newBlockStart - oldBlockStart;
  if (selection instanceof NodeSelection) {
    tr.setSelection(NodeSelection.create(tr.doc, selection.from + shift));
  } else {
    tr.setSelection(
      TextSelection.create(tr.doc, selection.from + shift, selection.to + shift),
    );
  }
  dispatch(tr.scrollIntoView());
  return true;
}

/**
 * Reorders content blocks: Alt+Shift+↑ / Alt+Shift+↓, or the toolbar's move
 * buttons. Images can also be dragged.
 */
export const MoveBlock = Extension.create({
  name: "moveBlock",

  addCommands() {
    return {
      moveBlock:
        (direction) =>
        ({ state, dispatch }) =>
          moveTopLevelBlock(state, direction, dispatch),
    };
  },

  addKeyboardShortcuts() {
    return {
      "Alt-Shift-ArrowUp": () => this.editor.commands.moveBlock("up"),
      "Alt-Shift-ArrowDown": () => this.editor.commands.moveBlock("down"),
    };
  },
});
