import React from "react";
import style from "./Tag.module.css";
import getCompliedClassName from "../../utils/getCompliedClassName";
import getCompliedCustomId from "../../utils/getCompliedCustomId";
import PropTypes from "prop-types";
import tagPropTypes, { defaultProps, propsDescription } from "./Tag.propTypes";
import constantProps from "./Tag.constantProps";

export default function Tag(props) {
  let {
    text,
    title,
    children,
    textEllipsis,

    size,
    shape,
    variant,
    color,

    disabled,

    startIcon,
    endIcon,

    customClassName,
    customId,

    ariaLabel,
    role = "tag",
    tabIndex,

    tagAttributeProps
  } = props;

  let ariaLabelValue = ariaLabel || text;
  
  let className = getCompliedClassName(
    customClassName,
    {
      [style.base]: true,
      [style.ellipsis]: !!textEllipsis,

      [style[size]]: !!size,
      [style[shape]]: !!shape,
      [style[variant]]: !!variant,
      [style[color]]: !!color,

      [style.disabled]: !!disabled,

      [style.start_icon]: !!startIcon,
      [style.end_icon]: !!endIcon
    },
    {
      [customClassName.base]: !!customClassName.base,
      [customClassName.textEllipsis]: !!customClassName.textEllipsis,

      [customClassName.size]: !!customClassName.size,
      [customClassName.shape]: !!customClassName.shape,
      [customClassName.variant]: !!customClassName.variant,
      [customClassName.color]: !!customClassName.color,

      [customClassName.disabled]: !!customClassName.disabled,

      [customClassName.start_icon]: !!customClassName.start_icon,
      [customClassName.end_icon]: !!customClassName.end_icon
    }
  );


  return (
    <span
      className={className}
      data-id={getCompliedCustomId(props, customId.tag)}
      aria-label={ariaLabelValue}
      role={role}
      tabIndex={tabIndex}
      {...tagAttributeProps}
      title={title || text}
    >
      <RenderAsIcon icon={startIcon} className={style.start_icon} />
      {text && (startIcon || startIcon) ? <span>{text}</span> : text || null}
      {!text && children ? children : null}
      <RenderAsIcon icon={endIcon} className={style.end_icon} />
    </span>
  );
}

Tag.propTypes = tagPropTypes;
Tag.defaultProps = defaultProps;
Tag.propsDescription = propsDescription;
Tag.constantProps = constantProps;

const RenderAsIcon = (props) => {
  return props.icon ? (
    <span className={props.className}>{props.icon}</span>
  ) : null;
};

RenderAsIcon.propTypes = {
  icon: PropTypes.any,
  className: PropTypes.string
};
