'use client'

import * as React from 'react'
import type { NodeViewProps } from '@tiptap/react'
import { ContentEditorMediaGalleryBlock } from '@admin/components/custom/content-editor/media-gallery-block'
import { focusNextNode } from '@admin/utils/editor/focus-next-node'
import { getMediaLabel } from '@admin/utils/editor/get-media-label'
import { isValidPosition } from '@admin/utils/editor/is-valid-position'
import { NodeViewWrapper } from '@tiptap/react'

export const MediaGalleryPlaceholderNode: React.FC<NodeViewProps> = (props) => {
  const { accept } = props.node.attrs
  const { editor, node } = props
  const extension = props.extension

  const removePlaceholder = React.useCallback(() => {
    const pos = props.getPos()
    if (!isValidPosition(pos)) return

    editor
      .chain()
      .focus()
      .deleteRange({ from: pos, to: pos + node.nodeSize })
      .run()
    focusNextNode(editor)
  }, [editor, node.nodeSize, props])

  const handleMediaSelected = React.useCallback(
    (url: string) => {
      const pos = props.getPos()
      if (!isValidPosition(pos) || !url) return
      const label = getMediaLabel(url)

      editor
        .chain()
        .focus()
        .deleteRange({ from: pos, to: pos + node.nodeSize })
        .insertContentAt(pos, {
          type: extension.options.type,
          attrs: {
            ...extension.options,
            src: url,
            alt: label,
            title: label
          }
        })
        .run()

      focusNextNode(editor)
    },
    [editor, extension.options, node.nodeSize, props]
  )

  return (
    <NodeViewWrapper className="block" tabIndex={0}>
      <ContentEditorMediaGalleryBlock
        accept={accept}
        disabled={!editor.isEditable}
        onMediaSelected={handleMediaSelected}
        onRemove={removePlaceholder}
      />
    </NodeViewWrapper>
  )
}
