import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useRef, useContext } from 'react';
import clsx from 'clsx';
import { CSSTransition } from 'react-transition-group';
import { Cross } from '@react-vant/icons';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';

const Tag = props => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('tag', prefixCls);
  const nodeRef = useRef(null);

  const onClose = event => {
    event.stopPropagation();

    if (props.onClose) {
      props.onClose(event);
    }
  };

  const getStyle = useMemo(() => {
    if (props.plain) {
      return {
        color: props.textColor || props.color,
        borderColor: props.color
      };
    }

    return {
      color: props.textColor,
      background: props.color
    };
  }, [props.textColor, props.color, props.plain]);

  const renderTag = () => {
    const {
      type,
      mark,
      plain,
      round,
      size,
      closeable
    } = props;
    const classes = {
      mark,
      plain,
      round
    };

    if (size) {
      classes[size] = size;
    }

    const CloseIcon = closeable && _jsx(Cross, {
      className: clsx(bem('close')),
      onClick: onClose
    });

    return _jsxs("span", Object.assign({
      ref: nodeRef,
      style: Object.assign(Object.assign({}, getStyle), props.style),
      className: clsx(props.className, bem([classes, type])),
      onClick: props.onClick
    }, {
      children: [props.children, CloseIcon]
    }));
  };

  return _jsx(CSSTransition, Object.assign({
    nodeRef: nodeRef,
    classNames: "rv-fade",
    in: props.show,
    timeout: 300,
    unmountOnExit: true
  }, {
    children: renderTag()
  }));
};

Tag.defaultProps = {
  show: true,
  type: 'default'
};
export default Tag;