import React, { useEffect, useRef, useState } from 'react'
import { Tag, Input, Tooltip, Icon } from 'antd'

export default React.forwardRef((props,ref) => {
  const [tags, setTags] = useState([])
  const [inputVisible, setInputVisible] = useState(false)
  const [inputValue, setInputValue] = useState()
  const inputRef = useRef()
  const dataInited = useRef(false)

  const handleClose = removedTag => {
    const newTags = tags.filter(tag => tag !== removedTag)
    setTags(newTags)
  }

  const handleInputChange = e => {
    setInputValue(e.target.value)
  }

  const handleInputConfirm = () => {
    if (inputValue && tags.indexOf(inputValue) === -1) {
      const newTags = [...tags, inputValue]
      setTags(newTags)
      setInputValue()
    }
  }

  const showInput = () => {
    setInputVisible(true)
    if (inputRef.current) {
      inputRef.current.focus()
    }
  }

  // 如果 prop.value 有更新
  useEffect(() => {
    if (props.value && !dataInited.current) {
      setTags((props.value || '').split(',').filter(Boolean))
      dataInited.current = true
    }
  }, [props.value])
  
  // 如果 tag 有更新
  useEffect(() => {
    const newValue = tags.join(',')
    if (props.value != newValue) {
      props.onChange && props.onChange(newValue)
    }
  }, [tags, props.value])

  return (
    <div ref={ref}>
      {tags.map(tag => {
        const isLongTag = tag.length > 20
        const tagElem = (
          <Tag key={tag} closable onClose={() => handleClose(tag)}>
            {isLongTag ? `${tag.slice(0, 20)}...` : tag}
          </Tag>
        )
        return isLongTag ? (
          <Tooltip title={tag} key={tag}>
            {tagElem}
          </Tooltip>
        ) : (
          tagElem
        )
      })}
      {inputVisible && (
        <Input
          ref={inputRef}
          type="text"
          size="small"
          style={{ width: 78 }}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      )}
      {!inputVisible && (
        <Tag onClick={showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
          <Icon type="plus" /> 新建
        </Tag>
      )}
    </div>
  )
})
