import type { Editor } from "@tiptap/react"
import { buildDriveDrawEditHref } from "@/lib/drive/drive-url"
import { parseGraphicAttrs } from "@/lib/drive/docs-graphic-types"

export const DOCS_GRAPHIC_DRAW_EVENT = "ultidocs:graphic-draw-open"
export const DOCS_GRAPHIC_DRAW_SAVED_EVENT = "ultidocs:graphic-draw-saved"

export function openDocsGraphicDrawModal() {
  window.dispatchEvent(new CustomEvent(DOCS_GRAPHIC_DRAW_EVENT))
}

/** Open inline draw modal, or UltiDraw in a new tab when linked to Drive. */
export function openDocsGraphicDrawEditor(editor?: Editor | null) {
  const attrs = readSelectedGraphicAttrs(editor ?? null)
  if (attrs?.drawDriveFileId) {
    window.open(buildDriveDrawEditHref(attrs.drawDriveFileId), "_blank", "noopener,noreferrer")
    return
  }
  openDocsGraphicDrawModal()
}

export function notifyDocsGraphicDrawSaved() {
  window.dispatchEvent(new CustomEvent(DOCS_GRAPHIC_DRAW_SAVED_EVENT))
}

export function readSelectedGraphicAttrs(editor: Editor | null) {
  if (!editor) return null
  if (editor.isActive("docsGraphic")) {
    return parseGraphicAttrs(editor.getAttributes("docsGraphic") as Record<string, unknown>)
  }
  if (editor.isActive("docsInlineGraphic")) {
    return parseGraphicAttrs(
      editor.getAttributes("docsInlineGraphic") as Record<string, unknown>
    )
  }
  return null
}

export type DocsGraphicDrawSavePayload = {
  drawScene: string
  src: string
  width: number
  height: number
}
