import React from "react";
import PropTypes from "prop-types";
import style from "./Button.module.css";
import getCompliedClassName from "../../utils/getCompliedClassName";
import { useButton } from "../../accessibility-utils/eventHandling";
import buttonPropTypes, {
  defaultProps,
  propsDescription
} from "./Button.propTypes";
import constantProps from "./Button.constantProps";
import getCompliedCustomId from "../../utils/getCompliedCustomId";

export default function Button(props) {
  let {
    text,
    children,
    textEllipsis,
    size,
    shape,
    variant,
    color,
    active,
    hovered,
    disabled,
    cursor,
    startIcon,
    endIcon,
    customClassName,
    customId,
    isStretch,
    tagAttributeProps
  } = props;
  let hasIcon = startIcon || endIcon;
  let className = getCompliedClassName(
    customClassName,
    {
      [style.base]: true,
      [style[size]]: !!size,
      [style[shape]]: !!shape,
      [style[variant]]: !!variant,
      [style[color]]: !!color,
      [style.ellipsis]: !!textEllipsis,
      [style[cursor]]: !!cursor,
      [style.content]: !!(startIcon || endIcon || children),
      [style.stretch]: !!isStretch,

      [style.active]: !!active,
      [style.hovered]: !!hovered,
      [style.disabled]: !!disabled
    },
    {
      [customClassName.size]: !!customClassName.size,
      [customClassName.shape]: !!customClassName.shape,
      [customClassName.variant]: !!customClassName.variant,
      [customClassName.color]: !!customClassName.color,
      [customClassName.textEllipsis]: !!customClassName.textEllipsis,
      [customClassName.cursor]: !!customClassName.cursor,

      [customClassName.active]: !!customClassName.active,
      [customClassName.hovered]: !!customClassName.hovered,
      [customClassName.disabled]: !!customClassName.disabled
    }
  );
  let { buttonProps } = useButton(props);
  return (
    <button
      className={className}
      {...buttonProps}
      data-id={getCompliedCustomId(props, customId.button)}
      {...tagAttributeProps}
    >
      <RenderAsIcon icon={startIcon} className={style.start_icon} />
      {text && hasIcon ? (
        <span className={style.content_text}>{text}</span>
      ) : (
        text || null
      )}
      {!text && children ? children : null}
      <RenderAsIcon icon={endIcon} className={style.end_icon} />
    </button>
  );
}

Button.propTypes = buttonPropTypes;
Button.defaultProps = defaultProps;
Button.propsDescription = propsDescription;
Button.constantProps = constantProps;

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

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