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

const ChapterItemModal = (props, ref) => {
  const { editor, setSectionInfo, sectionInfo, setSectionVisible } = props
  const [form] = Form.useForm()

  // 是否更新的判断
  const [bgColorValue, setBgColorValue] = useState('#000000')
  const [textColor, setTextColor] = useState('#ffffff')
  const [nowRandom, setNowRandom] = useState(null)
  const [initValues, setInitValues] = useState({
    title: '',
    textColor: textColor,
    align: 'center',
    size: 24,
    bgColor: bgColorValue,
    height: 100,
    family: '黑体'
  })

  useEffect(() => {
    if (sectionInfo && Object.entries(sectionInfo).length > 0) {
      setInitValues({ ...sectionInfo })
      form.setFieldsValue({ ...sectionInfo })
      setNowRandom(sectionInfo.random)
      setTextColor(sectionInfo.textColor)
      setBgColorValue(sectionInfo.bgColor)
      setSectionInfo({})
    }
  }, [sectionInfo])

  const bgColorChange = value => {
    const hex = typeof value === 'string' ? value : value?.toHexString()
    setBgColorValue(hex)
    form.setFieldsValue({ bgColor: hex })
  }
  const textColorChange = value => {
    const hex = typeof value === 'string' ? value : value?.toHexString()
    setTextColor(hex)
    form.setFieldsValue({ textColor: hex })
  }

  const callback = ({ title, random, bgColor, textColor, align, height, size }) => {
    form.setFieldsValue({
      title: title,
      bgColor: bgColor,
      textColor: textColor,
      align: align,
      height: height,
      size: size
    })
    setNowRandom(random)
  }

  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, path] = nodeEntry
      if (node.children[0].text === '') {
        SlateTransforms.removeNodes(editor)
      }
    }

    if (nowRandom) {
      const nodeEntries = SlateEditor.nodes(editor, {
        match: node => {
          // JS syntax
          if (SlateElement.isElement(node)) {
            if (node.type === 'chapterSection') {
              return true // 匹配 chapterHeader
            }
          }
          return false
        },
        universal: true
      })

      if (nodeEntries) {
        for (let nodeEntry of nodeEntries) {
          const [node, path] = nodeEntry
          // console.log(node, path);
          if (parseInt(node.random) === parseInt(nowRandom)) {
            SlateTransforms.setNodes(editor, { ...node, ...values }, { at: path })

            form.resetFields()
            setSectionVisible(false)
            return false
          }
        }
      }

      return
    }
    let random = Math.random().toString(10).substring(2, 10)

    editor.insertNode({
      type: 'chapterSection',
      title: values.title,
      textColor: values.textColor,
      bgColor: values.bgColor,
      random: random,
      align: values.align,
      height: values.height ? values.height : 200,
      size: values.size ? values.size : 20,
      family: values.family,
      callback: callback,
      children: [{ text: '' }]
    })

    form.resetFields()
    setSectionVisible(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="title"
            rules={[{ required: true, message: '请输入节头标题' }]}
            extra="最多输入30字">
            <Input maxLength={30} placeholder="" allowClear />
          </Form.Item>

          <Form.Item>
            <Row gutter={20}>
              <Col span={12}>
                <div className="justcontent-color-inline">
                  <Form.Item
                    label="背景颜色"
                    name="bgColor"
                    className="flex-max"
                    rules={[{ pattern: /^#[0-9A-Fa-f]{6}$/i, message: '请输入正确的16进制色值' }]}>
                    <Input maxLength={100} placeholder="" allowClear />
                  </Form.Item>
                  <Form.Item label={` `}>
                    <ColorPicker
                      disabledAlpha
                      format="hex"
                      value={bgColorValue}
                      defaultValue={bgColorValue}
                      onChange={bgColorChange}
                    />
                  </Form.Item>
                </div>
              </Col>
              <Col span={12}>
                <div className="justcontent-color-inline">
                  <Form.Item
                    label="文本颜色"
                    name="textColor"
                    className="flex-max"
                    rules={[{ pattern: /^#[0-9A-Fa-f]{6}$/i, message: '请输入正确的16进制色值' }]}>
                    <Input placeholder="" allowClear />
                  </Form.Item>
                  <Form.Item label={` `}>
                    <ColorPicker
                      disabledAlpha
                      format="hex"
                      value={textColor}
                      defaultValue={textColor}
                      onChange={textColorChange}
                    />
                  </Form.Item>
                </div>
              </Col>
              <Col span={12}>
                <Form.Item label="字体" name="family">
                  <Select>
                    {fontFamilyList.map((item, index) => {
                      return (
                        <Select.Option value={item.value} key={index}>
                          {item.name}
                        </Select.Option>
                      )
                    })}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="文字大小" name="size" rules={[{ required: true, message: '请输入文字大小' }]}>
                  <Select>
                    {fontSizeList.map((item, index) => {
                      return (
                        <Select.Option value={item.value} key={index}>
                          {item.name}
                        </Select.Option>
                      )
                    })}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="对齐方式" name="align" rules={[{ required: true, message: '请选择对齐方式' }]}>
                  <Select>
                    <Select.Option value="left">左对齐</Select.Option>
                    <Select.Option value="center">居中对齐</Select.Option>
                    <Select.Option value="right">右对齐</Select.Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="高度" name="height">
                  <InputNumber
                    controls={false}
                    placeholder=""
                    style={{ width: '100%', textAlign: 'left' }}
                    allowClear
                  />
                </Form.Item>
              </Col>
              <Col span={12}></Col>
            </Row>
          </Form.Item>
          <Form.Item className="editor-form-buttons">
            <Space>
              <Button type="default" onClick={() => setSectionVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {nowRandom ? '更新' : '插入'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default forwardRef(ChapterItemModal)
