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

export default React.forwardRef((props, ref) => {
  const { tags = [], pois = [], type, onPoiDelete, onDelete, onChange } = props

  const inputRef = useRef()
  const [inputValue, setInputValue] = useState()
  const [inputVisible, setInputVisible] = useState(false)

  const handleClose = (tag) => {
    if (tag.id && onPoiDelete) {
      onPoiDelete(type, tag)
      return
    }

    if (onDelete) {
      onDelete(`building${type}`, tag)
    }
  }

  const handleInputConfirm = () => {
    const exists = tags.concat(pois).filter((tag) => tag.name === inputValue)[0]
    if (!exists) {
      onChange(`building${type}`, tags.concat({ name: inputValue }))
    }
    setInputVisible(false)
    setInputValue()
  }

  return (
    <div>
      {
        tags.concat(pois).map((tag) => (
          <Tag key={tag.name} closable onClose={() => handleClose(tag)}>
            <Typography.Text>{tag.name}</Typography.Text>
          </Tag>
        ))
      }
      {
        inputVisible ? (
          <Input
            ref={inputRef}
            type="text"
            size="small"
            style={{ width: 80, display: inputVisible ? 'inline-block' : 'none' }}
            value={inputValue}
            onChange={e => setInputValue(e.target.value)}
            onBlur={handleInputConfirm}
            onPressEnter={handleInputConfirm}
          />
        ) : (
          <Tag onClick={() => setInputVisible(true)} style={{ background: '#fff', borderStyle: 'dashed' }}>
            <Icon type="plus" /> 新建
          </Tag>
        )
      }
    </div>
  )
})
