import { Extension, type Editor } from "@tiptap/core"
import { Plugin, PluginKey } from "@tiptap/pm/state"
import {
  docsEditFindReplace,
  docsEditPastePlain,
} from "@/lib/drive/docs-edit-actions"
import type { DocsShortcutId } from "@/lib/drive/docs-keyboard-shortcuts-config"
import { useDocsKeyboardShortcutsStore } from "@/lib/stores/docs-keyboard-shortcuts-store"

const PLUGIN_KEY = new PluginKey("docsEditorShortcuts")

function runEditorShortcut(id: DocsShortcutId, editor: Editor): boolean {
  switch (id) {
    case "edit.redo":
      return editor.commands.redo()
    case "edit.pastePlain":
      void docsEditPastePlain(editor)
      return true
    case "edit.findReplace":
      docsEditFindReplace(editor)
      return true
    default:
      return false
  }
}

/** Editor shortcuts driven by the centralized docs keyboard-shortcuts config/store. */
export const DocsEditorShortcuts = Extension.create({
  name: "docsEditorShortcuts",
  addProseMirrorPlugins() {
    const editor = this.editor

    return [
      new Plugin({
        key: PLUGIN_KEY,
        props: {
          handleKeyDown: (_view, event) => {
            const id = useDocsKeyboardShortcutsStore.getState().matchEvent(
              event,
              (definition) =>
                definition.scope === "editor" && definition.handler === "custom"
            )
            if (!id) return false
            if (!runEditorShortcut(id, editor)) return false
            event.preventDefault()
            return true
          },
        },
      }),
    ]
  },
})
