import type { Editor } from "@tiptap/react"
import { toast } from "sonner"

function focusEditorView(editor: Editor) {
  editor.commands.focus()
  editor.view.focus()
}

export function docsEditCanUndo(editor: Editor | null): boolean {
  if (!editor) return false
  return editor.can().chain().focus().undo().run()
}

export function docsEditCanRedo(editor: Editor | null): boolean {
  if (!editor) return false
  return editor.can().chain().focus().redo().run()
}

export function docsEditUndo(editor: Editor | null) {
  if (!editor) return
  editor.chain().focus().undo().run()
}

export function docsEditRedo(editor: Editor | null) {
  if (!editor) return
  editor.chain().focus().redo().run()
}

export function docsEditCut(editor: Editor | null) {
  if (!editor) return
  focusEditorView(editor)
  document.execCommand("cut")
}

export function docsEditCopy(editor: Editor | null) {
  if (!editor) return
  focusEditorView(editor)
  document.execCommand("copy")
}

export function docsEditPaste(editor: Editor | null) {
  if (!editor) return
  focusEditorView(editor)
  document.execCommand("paste")
}

export async function docsEditPastePlain(editor: Editor | null) {
  if (!editor) return
  try {
    const text = await navigator.clipboard.readText()
    editor.chain().focus().deleteSelection().insertContent(text).run()
  } catch {
    toast.error("Impossible de coller le texte")
  }
}

export function docsEditSelectAll(editor: Editor | null) {
  if (!editor) return
  editor.chain().focus().selectAll().run()
}

export function docsEditDeleteSelection(editor: Editor | null) {
  if (!editor) return
  if (!editor.state.selection.empty) {
    editor.chain().focus().deleteSelection().run()
    return
  }
  editor.chain().focus().deleteForward().run()
}

export function docsEditFindReplace(_editor: Editor | null) {
  toast.info("Rechercher et remplacer — bientôt disponible")
}
