import React, {useCallback} from 'react'
import {Transforms, Range, Editor} from 'slate'
import {Editable, ReactEditor} from '5e-slate-react'
import {useEditorContext} from '../hooks/useEditContext'
import Element from '../element'
import Leaf from '../leaf'
import {insertMention} from '../global/tool'

interface MentionsProps {
  index: number
  search: string
  target: any
  chars: any[]
  classNames?: string
  setIndex(i: number): void
  setTarget(t: any): void
}
const EVENT_PREVENT_DEFAULT = ['ArrowDown', 'ArrowUp', 'Tab', 'Enter', 'Escape']
export const EditorWrapper = ({
  readonly,
  mentionProps,
}: {
  readonly: boolean
  mentionProps: MentionsProps
}) => {
  const editorContext = useEditorContext()
  const {editor} = editorContext
  const renderElement = useCallback(elementProps => <Element {...elementProps} />, [])
  const renderLeaf = useCallback(leafProps => <Leaf {...leafProps} />, [])
  const {index, search, target, setIndex, setTarget, chars, classNames} = mentionProps

  const eventKeyBind = (event: React.KeyboardEvent) => {
    // console.error(search, '----')
    if (event.key === '@') {
      sessionStorage.setItem('isFirstMention', 'ok')
    } else {
      sessionStorage.setItem('isFirstMention', '')
    }
    if (target) {
      if (EVENT_PREVENT_DEFAULT.includes(event.key)) {
        event.preventDefault()
      }
      if (event.key === 'ArrowDown') {
        const prevIndex = index >= chars.length - 1 ? 0 : index + 1
        setIndex(prevIndex)
      }
      if (event.key === 'ArrowUp') {
        const nextIndex = index <= 0 ? chars.length - 1 : index - 1
        setIndex(nextIndex)
      }
      if (event.key === 'Tab' || event.key === 'Enter') {
        if (chars.length !== 0 && chars[index]) {
          // 选中画线的模块
          Transforms.select(editor, target)
          insertMention(editor, chars[index])
          Transforms.insertText(editor, ' ')
          ReactEditor.focus(editor)
        }
        setTarget(null)
      }
      if (event.key === 'Escape') {
        setTarget(null)
      }
    }
  }
  const onKeyDown = useCallback(eventKeyBind, [index, search, target, editor.selection, chars])
  return (
    <Editable
      autoFocus
      className={`editable-content ${classNames}`}
      onKeyDown={onKeyDown}
      readOnly={readonly}
      renderElement={renderElement}
      renderLeaf={renderLeaf}
      spellCheck
    />
  )
}

export default EditorWrapper
