import React, { useEffect, useRef, useState } from 'react';
import { Select, Space, Divider, Input, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import styles from './index.less';

const CustomSelect = props => {
  const [name, setName] = useState('');
  const [items, setItems] = useState([]);

  const inputRef = useRef(null);

  const onNameChange = e => {
    setName(e.target.value);
  };

  const addItem = e => {
    e.preventDefault();
    const v = name.trim();
    if (v) {
      setItems([...items, { name: v }]);
      setName('');
      setTimeout(() => {
        // eslint-disable-next-line no-unused-expressions
        inputRef.current?.focus();
      }, 0);
    }
  };

  const onChange = e => {
    props.onChange(e);
  };

  useEffect(() => {
    setItems(props.options);
  }, [props.options]);

  return (
    <Select
      mode={props.mode}
      maxTagTextLength={8}
      allowClear
      value={props.value}
      onChange={onChange}
      dropdownRender={menu => (
        <>
          {menu}
          {props.isCustom && (
            <>
              <Divider className={styles.SelectDivider} />
              <Space className={styles.SelectSpace}>
                <Input
                  className={styles.SelectInput}
                  placeholder={$t('enter.custom.attribute')}
                  ref={inputRef}
                  value={name}
                  maxLength={30}
                  onChange={onNameChange}
                />
                <Button type="primary" icon={<PlusOutlined />} onClick={addItem} />
              </Space>
            </>
          )}
        </>
      )}
      options={items.map(item => ({ label: item.name, value: JSON.stringify(item) }))}
    ></Select>
  );
};

export default CustomSelect;
