import React, { useState, useRef } from 'react';
import { Input, Tag } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import styles from '../../style.less';

const InsertTag = options => {
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const refInput = useRef();
  const showInput = () => {
    setInputVisible(true);
    const timer = setTimeout(() => {
      if (refInput.current) {
        refInput.current.focus();
      }
      clearTimeout(timer);
    }, 1);
  };
  const handleInputChange = e => {
    setInputValue(e.target.value || '');
  };
  const handleInputConfirm = () => {
    setInputVisible(false);
    setInputValue('');
  };

  return (
    <>
      {inputVisible && (
        <Input
          type="text"
          size="small"
          ref={refInput}
          className={styles['groupBox-body--tag-input']}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      )}
      {!inputVisible && (
        <Tag
          className={[styles['groupBox-body--tag'], styles['groupBox-body--new']]}
          color="blue"
          onClick={showInput}
        >
          <PlusOutlined /> 添加
        </Tag>
      )}
    </>
  );
};

export default InsertTag;
