import Quill from 'quill/core'
import Embed from 'quill/blots/embed'

class TemplateInputPromptBlot extends Embed {
  static blotName = 'template-input-prompt'
  static tagName = 'span'
  static className = 'template-input-prompt-container'

  static create(config: { placeholder: string; index: string }) {
    const root = super.create() as HTMLElement

    root.classList.add(`prompt-index-${config.index}`)

    // root.classList.add('prompt-blank', 'relative')

    const outerEl = document.createElement('span')
    outerEl.dataset.placeholder = `[${config.placeholder}]`
    // outerEl.classList.add('prompt-blank', 'relative', 'inline-block', 'min-w-fit')
    outerEl.classList.add(
      'relative',
      'inline-block',
      // 'bg-[rgb(0,87,255)]',
      'px-[6px]',
      // 'py-[2px]',
      'mx-[2px]',
      'rounded-[4px]',
    )
    outerEl.style.backgroundColor = 'rgba(0,87,255,0.06)'
    // outerEl.style.color = '#b5caff'
    outerEl.style.color = '#9ea3ff'
    outerEl.style.lineHeight = '24px'

    const placeholderEl = document.createElement('span')
    placeholderEl.textContent = `[${config.placeholder}]`

    outerEl.appendChild(placeholderEl)

    const inputContainerEl = document.createElement('span')
    inputContainerEl.setAttribute('contenteditable', 'true')
    inputContainerEl.classList.add(
      'prompt-content',
      // 'inline-block',
      'absolute',
      'z-1',
      // 'min-w-full',
      // 'left-0',
      // 'right-0',
      'px-[6px]',
      // 'text-[#0057ff]',
      'whitespace-pre-wrap',
      'break-all',
      // 'outline-none',
    )

    inputContainerEl.style.left = '0'
    inputContainerEl.style.right = '0'
    inputContainerEl.style.color = '#000dff'
    inputContainerEl.style.outlineStyle = 'none'

    inputContainerEl.textContent = ''

    // 事件绑定
    inputContainerEl.addEventListener('keydown', (e) => {
      if (e.key === 'Backspace') {
        e.stopPropagation()
      }
    })
    inputContainerEl.addEventListener('input', (e) => {
      const target = e.target as HTMLSpanElement

      if (target.textContent?.length !== 0) {
        placeholderEl.classList.remove('inline-block')
        placeholderEl.classList.add('hidden')

        inputContainerEl.classList.remove('absolute', 'px-[6px]')
      } else {
        placeholderEl.classList.remove('hidden')
        placeholderEl.classList.add('inline-block')

        inputContainerEl.classList.add('absolute', 'px-[6px]')
      }
    })

    outerEl.appendChild(inputContainerEl)

    root.appendChild(outerEl)

    return root
  }
}

Quill.register(TemplateInputPromptBlot)
