import { useState, forwardRef, useImperativeHandle } from 'react'
import { Divider, Input, Space, Button, Form, ColorPicker } from 'antd'

import { SlateTransforms, SlateEditor, SlateElement } from '@wangeditor/editor'

import { setPracticeRandom } from '@/store/modules/editor'
import { useDispatch } from 'react-redux'
import './index.less'

const PracticeModal = (props, ref) => {
  const { bookId, chapterId, setPracticeOpenVisible } = props
  const dispatch = useDispatch()
  const { editor } = props
  const [form] = Form.useForm()
  const [themeValue, setThemeValue] = useState('#ab1941')
  const [initValues, setInitValues] = useState({ practice: '', theme: '#ab1941' })
  const [nodes, setNodes] = useState(null)

  useImperativeHandle(ref, () => {
    return {
      nodes
    }
  })

  const textColorChange = value => {
    const hex = typeof value === 'string' ? value : value?.toHexString()
    setThemeValue(hex)
    form.setFieldsValue({ theme: hex })
  }

  const callback = (practiceNum, practiceTitle) => {
    const nodeEntries = SlateEditor.nodes(editor, {
      match: node => {
        // JS syntax
        if (SlateElement.isElement(node)) {
          if (node.type === 'chapterPractice') {
            return true
          }
        }
        return false
      },
      universal: true
    })

    setNodes(nodeEntries)
    dispatch(setPracticeRandom({ practiceNum, practiceTitle }))
  }

  const onFinish = values => {
    editor.restoreSelection()

    const nodeEntries = SlateEditor.nodes(editor, {
      match: node => {
        // JS syntax
        if (SlateElement.isElement(node)) {
          if (node.type === 'paragraph') {
            return true // 匹配 paragraph
          }
        }
        return false
      },
      universal: true
    })
    for (let nodeEntry of nodeEntries) {
      const [node] = nodeEntry
      if (node.children[0].text === '') {
        SlateTransforms.removeNodes(editor)
      }
    }

    const practiceNum = Math.random().toString(32).substring(2, 10)
    editor.insertNode({
      type: 'chapterPractice',
      title: values.practice,
      practiceNum: practiceNum,
      bookId,
      chapterId,
      theme: values.theme,
      callback: callback,
      children: [{ text: '' }]
    })
    form.resetFields()
    setPracticeOpenVisible(false)
    editor.focus()
  }

  return (
    <div>
      <Divider />
      <div className="editor-content-form">
        <Form layout="vertical" name="validate_other" form={form} onFinish={onFinish} initialValues={initValues}>
          <Form.Item
            label="标题"
            name="practice"
            rules={[{ required: true, message: '请输入标题' }]}
            extra="最多输入100字">
            <Input maxLength={100} placeholder="" allowClear />
          </Form.Item>
          <Form.Item>
            <div className="justcontent-color-inline">
              <Form.Item
                label="练习主题色"
                name="theme"
                className="flex-max"
                rules={[
                  { required: true, message: '请选择颜色' },
                  { pattern: /^#[0-9A-Fa-f]{6}$/i, message: '请输入正确的16进制色值' }
                ]}>
                <Input placeholder="" allowClear />
              </Form.Item>
              <Form.Item label={` `}>
                <ColorPicker
                  disabledAlpha
                  value={themeValue}
                  defaultValue={themeValue}
                  format="hex"
                  onChange={textColorChange}
                />
              </Form.Item>
            </div>
          </Form.Item>
          <Form.Item className="editor-form-buttons">
            <Space>
              <Button type="default" onClick={() => setPracticeOpenVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                插入
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default forwardRef(PracticeModal)
