import {memo, useMemo} from 'react';
import {useState} from 'react';
import {Tag} from 'antd';
import {TweenOneGroup} from 'rc-tween-one';
import {styled} from 'styled-components';
import {CloseCircleFilled} from '@ant-design/icons';

/** 支持两种格式的options
 * ["tag1","tag2","tag3"]
 *
 * [{
 *    option:"tag1"
 *    value:"value"
 *  }]
 * */
export const EditableTags = memo(({
  onClose,
  onSelect,
  options,
  closable=false,
  style,
  tagStyle
}) => {
  const [check, setCheck] = useState({})

  const handleClose = (removedTag) => {
    onClose&&onClose(options.filter(tag => tag.id!==removedTag.id));
  }

  const handleSelect = (tag)=>{
    onSelect && onSelect(tag)
    setCheck(tag)
  }

  const children =useMemo(()=>
      (options||[]).map(tag =>
      <span style={{display: 'inline-block',...tagStyle}}>
        <CustomTag
          key={tag.id}
          closable={closable && check.id === tag.id}
          color={check.id === tag.id ? "blue" : "default"}
          onClick={() => handleSelect(tag)}
          closeIcon={<CloseIcon style={{fontSize: 12}}/>}
          onClose={(e) => {
            e.preventDefault();
            handleClose(tag);
          }}
        >
          {tag?.label}
        </CustomTag>
      </span>
    )
  ,[check,options])

  return (
    <Container style={style}>
      <TweenOneGroup
        appear={false}
        enter={{
          scale: 0.8,
          opacity: 0,
          type: 'from',
          duration: 100,
        }}
        leave={{
          opacity: 0,
          width: 0,
          scale: 0,
          duration: 200,
        }}
        onEnd={(e) => {
          if (e.type === 'appear' || e.type === 'enter') {
            e.target.style = 'display: inline-block';
          }
        }}
      >
        { children }
      </TweenOneGroup>
    </Container>
  );
})

const Container = styled.div`
  width: 97%;
  padding-block-end: 15px;
  padding-block-start: 15px;
  padding-inline-end: 20px;
  padding-inline-start: 20px;
  background-color: ${p=>p.theme.colorBgTextHover};
  // min-height: 68px;
  margin-bottom: ${p=>p.theme.margin + 'px'};
`

const CustomTag = styled(Tag)`
  cursor: pointer;
  font-size: ${p => p.theme.fontSize + 'px'};
  padding: ${p => p.theme.paddingXS + 'px'} ${p => p.theme.padding + 'px'};
  border-radius: ${p => p.theme.borderRadius + 'px'} ;
`

const CloseIcon =styled(CloseCircleFilled)`
  position:absolute;
  top:0;
  right:0;
  margin: -5px -5px 0 0;
`
