import React, {useCallback, useMemo, useState} from 'react'
import {Editable, withReact, Slate} from '5e-slate-react'
import {createEditor, Descendant} from 'slate'
import {withHistory} from 'slate-history'

import Element from '../element'
import Leaf from '../leaf'
import {EditorProvider} from './editor_context'
import {EditorType} from '../global/interface'
import {withMentions} from '../plugins/withMentions'

interface Props {
  // 渲染元素
  element?: any[]
  // readonly 编辑器是否
  readonly: boolean
  // value
  data?: any
  // changeValue
  changeValue?(s: any): void
}

const PureEditor = (baseProps: Partial<Props> = {}) => {
  const {data} = baseProps
  const [value] = useState<Descendant[]>(data)

  const editor = useMemo<EditorType>(
    () => withMentions(withHistory(withReact(createEditor() as any))),
    []
  )

  const changeValues = () => void 0
  // 键盘输入 特殊符号时 触发相应的逻辑
  return (
    <EditorProvider editor={editor}>
      <Slate editor={editor} onChange={changeValues} value={value}>
        <EditorWrapper />
      </Slate>
    </EditorProvider>
  )
}

export const EditorWrapper = ({
  readonly,
  mentionProps,
}: {
  readonly?: boolean
  mentionProps?: any
}) => {
  const renderElement = useCallback(elementProps => <Element {...elementProps} />, [])
  const renderLeaf = useCallback(leafProps => <Leaf {...leafProps} />, [])

  return (
    <Editable
      autoFocus
      className="editable-content"
      placeholder=""
      readOnly={readonly}
      renderElement={renderElement}
      renderLeaf={renderLeaf}
      spellCheck
      style={{padding: 4, borderRadius: '4px'}}
      // style={{minHeight: '100%'}}
    />
  )
}

export default PureEditor

export type CustomText = {
  bold?: boolean
  italic?: boolean
  code?: boolean
  text: string
}

export type MentionElement = {
  type: 'mention'
  character: string
  children: CustomText[]
}
