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.dataset.placeholder = `${config.placeholder}`
    root.dataset.index = `${config.index}`

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

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

    const outerEl = document.createElement('span')
    // 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.cssText = 'background-color: rgba(0,87,255,0.06); color: #b5caff; line-height: 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.cssText = `
      left: 0;
      right: 0;
      color: #000dff;
      outline-style: 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
  }

  static value(spanEl: HTMLSpanElement) {
    return {
      placeholder: spanEl.dataset.placeholder,
      index: spanEl.dataset.index,
    }
  }
}

Quill.register(TemplateInputPromptBlot)
