"use client"

import { useEffect, useMemo, useState } from "react"
import type { Editor } from "@tiptap/react"
import type { DocsEditMenuActions, DocsEditMenuState } from "@/components/drive/richtext/docs-edit-menu"
import {
  docsEditCanRedo,
  docsEditCanUndo,
  docsEditCopy,
  docsEditCut,
  docsEditDeleteSelection,
  docsEditFindReplace,
  docsEditPaste,
  docsEditPastePlain,
  docsEditRedo,
  docsEditSelectAll,
  docsEditUndo,
} from "@/lib/drive/docs-edit-actions"

export function useDocsEditMenu({
  editor,
  disabled,
}: {
  editor: Editor | null
  disabled?: boolean
}) {
  const [revision, setRevision] = useState(0)

  useEffect(() => {
    if (!editor || disabled) return

    const refresh = () => setRevision((value) => value + 1)
    editor.on("transaction", refresh)
    editor.on("selectionUpdate", refresh)
    return () => {
      editor.off("transaction", refresh)
      editor.off("selectionUpdate", refresh)
    }
  }, [disabled, editor])

  const state = useMemo<DocsEditMenuState>(
    () => ({
      canUndo: docsEditCanUndo(editor),
      canRedo: docsEditCanRedo(editor),
    }),
    [editor, revision]
  )

  const actions = useMemo<DocsEditMenuActions>(
    () => ({
      onUndo: () => docsEditUndo(editor),
      onRedo: () => docsEditRedo(editor),
      onCut: () => docsEditCut(editor),
      onCopy: () => docsEditCopy(editor),
      onPaste: () => docsEditPaste(editor),
      onPastePlain: () => void docsEditPastePlain(editor),
      onSelectAll: () => docsEditSelectAll(editor),
      onDelete: () => docsEditDeleteSelection(editor),
      onFindReplace: () => docsEditFindReplace(editor),
    }),
    [editor]
  )

  return {
    actions,
    state,
    disabled,
  }
}
