import { Extension } from "@tiptap/core"
import {
  applyDocsParagraphStyleById,
  extractParagraphStyleFromSelection,
} from "@/lib/drive/docs-paragraph-style-apply"

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    docsParagraphStyle: {
      applyDocsParagraphStyle: (styleId: string) => ReturnType
      updateDocsParagraphStyleFromSelection: (styleId: string) => ReturnType
    }
  }
}

export const DocsParagraphStyle = Extension.create({
  name: "docsParagraphStyle",

  addGlobalAttributes() {
    return [
      {
        types: ["paragraph", "heading"],
        attributes: {
          styleId: {
            default: null,
            parseHTML: (element) => element.getAttribute("data-style-id"),
            renderHTML: (attributes) => {
              const styleId = attributes.styleId as string | null | undefined
              if (!styleId) return {}
              return {
                "data-style-id": styleId,
                class: `docs-paragraph-style docs-paragraph-style--${styleId}`,
              }
            },
          },
        },
      },
    ]
  },

  addCommands() {
    return {
      applyDocsParagraphStyle:
        (styleId: string) =>
        ({ editor }) =>
          applyDocsParagraphStyleById(editor, styleId),
      updateDocsParagraphStyleFromSelection:
        (styleId: string) =>
        ({ editor }) => {
          const extracted = extractParagraphStyleFromSelection(editor, styleId)
          if (!extracted) return false
          editor.emit("docsParagraphStyleUpdate", { styleId, definition: extracted })
          return true
        },
    }
  },
})

export type DocsParagraphStyleUpdatePayload = {
  styleId: string
  definition: import("@/lib/drive/docs-paragraph-styles").DocParagraphStyleDefinition
}

declare module "@tiptap/core" {
  interface EditorEvents {
    docsParagraphStyleUpdate: DocsParagraphStyleUpdatePayload
  }
}
