import { useState, useEffect, forwardRef } from 'react'
import { Divider, Input, Space, Button, Form, message, Select, ColorPicker, Row, Col } from 'antd'
import { SlateTransforms, SlateEditor, SlateElement } from '@wangeditor/editor'
import './index.less'
import { addChapterTooltip, delChapterTooltip } from '../utils/request'
import { findNodeWithParent, fontSizeList } from '../utils/setting'

const TooltipModal = (props, ref) => {
  const { editor, bookId, chapterId, setTooltipVisible, setTooltipInfo, tooltipInfo, selectionSize = 18 } = props

  const [form] = Form.useForm()
  const tooltipTypeValue = Form.useWatch('tooltipType', form)
  const [loading, setLoading] = useState(false)
  const [themeValue, setThemeValue] = useState('#ab1941')
  const [initvalues, setInitValue] = useState({
    tooltipType: 1,
    title: '',
    link: '',
    content: '',
    theme: '#ab1941',
    fontSize: selectionSize || 18
  })
  const [toolStatus, setToolStatus] = useState(false)
  const [nowRandom, setNowRandom] = useState(null)
  const [fontsize, setFontsize] = useState(selectionSize)

  useEffect(() => {
    if (Object.entries(tooltipInfo).length > 0) {
      let obj = { ...tooltipInfo, tooltipType: parseInt(tooltipInfo.tooltipType), fontSize: parseInt(tooltipInfo.fontsize) }
      setInitValue(obj)
      form.setFieldsValue(obj)
      setThemeValue(tooltipInfo.theme)
      setNowRandom(tooltipInfo.random)
      setFontsize(parseInt(tooltipInfo.fontsize))
      setTooltipInfo({})
    }
  }, [tooltipInfo])

  const textColorChange = (value, hex) => {
    setThemeValue(hex)
    form.setFieldsValue({ theme: hex })
  }

  const onFinish = async values => {
    editor.restoreSelection()
    setLoading(true)
    const { tooltipType, link, theme, ...other } = values
    let newLink = ''
    if (link) {
      if (!/^https*:\/\//.test(link)) {
        newLink = `http://${link}`
      } else {
        newLink = link
      }
    }

    if (nowRandom) {
      const data = await addChapterTooltip({
        book_id: bookId,
        chapter_id: chapterId,
        position: nowRandom,
        link: newLink,
        ...other,
        type: tooltipType
      })

      if (data) {
        const props = { ...values, link: newLink, random: nowRandom, theme, fontsize: values.fontSize || selectionSize || fontsize }

        const aPath = findNodeWithParent(editor.children, 'chapterTooltip', 'random', nowRandom)
        SlateTransforms.setNodes(editor, props, { at: aPath.reverse() })
        message.success('更新成功!')
        setTooltipVisible(false)
        setNowRandom(null)
      }

      setLoading(false)
      return
    }

    let random = Math.random().toString(10).substring(2, 10)
    const data = await addChapterTooltip({
      book_id: bookId,
      chapter_id: chapterId,
      position: random,
      link: newLink,
      ...other,
      type: tooltipType
    })

    if (data) {
      editor.insertNode({
        type: 'chapterTooltip',
        title: values.title,
        tooltipType: parseInt(values.tooltipType),
        link: newLink,
        content: values.content,
        random,
        theme,
        fontsize: values.fontSize || selectionSize || fontsize,
        children: [{ text: '' }]
      })
      message.success('添加成功!')
    }
    setNowRandom(null)
    setTooltipVisible(false)
    setLoading(false)
  }

  const deleteNowTooltip = async () => {
    const data = await delChapterTooltip({
      book_id: bookId,
      chapter_id: chapterId,
      position: nowRandom
    })
    if (data) {
      editor.restoreSelection()
      const nodeEntries = SlateEditor.nodes(editor, {
        match: node => {
          // JS syntax
          if (SlateElement.isElement(node)) {
            if (node.type === 'chapterTooltip') {
              return true // 匹配 chapterToolTip
            }
          }
          return false
        },
        universal: true
      })
      // 遍历匹配的节点迭代器，获取匹配的节点路径
      let nodePaths = []
      let nodes = []
      if (nodeEntries === null) {
        console.log('当前未选中的 chapterTooltip')
      } else {
        for (let nodeEntry of nodeEntries) {
          const [node, path] = nodeEntry
          nodePaths.push(path)
          nodes.push(node)
        }
        // 将属性应用到匹配的节点
        for (const path of nodePaths) {
          SlateTransforms.removeNodes(editor, { at: path })
        }
      }
      setNowRandom(null)
      setTooltipVisible(false)
    }
  }

  return (
    <div>
      <Divider />
      <div className="editor-content-form">
        <Form layout="vertical" name="validate_other" form={form} onFinish={onFinish} initialValues={initvalues}>
          <Form.Item label="气泡类型" name="tooltipType" rules={[{ required: true, message: '请选择气泡类型' }]}>
            <Select disabled={nowRandom ? true : false}>
              <Select.Option value={1}>文字气泡</Select.Option>
              <Select.Option value={2}>图标气泡</Select.Option>
            </Select>
          </Form.Item>
          {tooltipTypeValue === 1 && (
            <Form.Item
              label="气泡标题"
              name="title"
              rules={[{ required: tooltipTypeValue === 1 ? true : false, message: '请输入气泡标题' }]}
              extra="最多输入100字">
              <Input maxLength={100} placeholder="" allowClear />
            </Form.Item>
          )}
          <Form.Item label="描述" name="content" rules={[{ required: true, message: '请输入描述内容' }]}>
            <Input.TextArea autoSize={{ minRows: 2, maxRows: 4 }} placeholder="" allowClear />
          </Form.Item>
          <Form.Item>
            <Row gutter={20}>
              <Col span={12}>
                <Form.Item label="字号" name="fontSize">
                  <Select>
                    {fontSizeList.map((item, index) => {
                      return (
                        <Select.Option value={item.value} key={index}>
                          {item.name}
                        </Select.Option>
                      )
                    })}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <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>
              </Col>
            </Row>
          </Form.Item>
          <Form.Item
            label="链接(非必须)"
            name="link"
            rules={[
              { required: false, message: '请输入气泡内容' },
              { pattern: /^https*:\/\//gi, message: '链接地址需要http(s)://开头' }
            ]}>
            <Input placeholder="" allowClear />
          </Form.Item>
          <Form.Item className="editor-form-buttons">
            <Space>
              {toolStatus && (
                <Button type="default" onClick={deleteNowTooltip}>
                  删除
                </Button>
              )}
              <Button type="primary" loading={loading} htmlType="submit">
                {nowRandom ? '更新' : '插入'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default forwardRef(TooltipModal)
