import PropTypes from 'prop-types';
import { Typography } from '@mui/material';
import isUndefined from 'lodash/isUndefined';

import colors from '../Colors';
import { mergeProps } from '../Util';
import { withDeprecated } from '../Util/deprecate';
import { styled } from '../Theme';

const types = {
  error: {
    color: colors.common.white,
    backgroundColor: colors.error.main,
  },
  warning: {
    color: colors.common.white,
    backgroundColor: colors.warning.main,
  },
  success: {
    color: colors.common.white,
    backgroundColor: colors.success.main,
  },
  primary: {
    color: colors.common.white,
    backgroundColor: colors.primary.main,
  },
  reverse: {
    color: colors.common.white,
    backgroundColor: colors.grey[900],
  },
};

/**
 * Badge component to display notification badge
 * @typedef {{
 *   children: import('react').ReactNode;
 *   content?: string;
 *   type?: 'error' | 'warning' | 'success' | 'primary' | 'reverse';
 *   className?: string;
 *   style?: object | string;
 * } & import('@mui/material').TypographyProps } BadgeProps
 */

/**
 * Badge notification component
 * @param {BadgeProps} props
 * @returns {JSX.Element}
 */
function Badge({ ...rawProps }) {
  const props = Object.assign({}, rawProps);
  if (isUndefined(props.type)) {
    props.type = 'primary';
  }
  if (isUndefined(props.content)) {
    props.content = '';
  }
  if (isUndefined(props.className)) {
    props.className = '';
  }
  if (isUndefined(props.style)) {
    props.style = {};
  }
  const newProps = mergeProps(props, Badge, ['style']);
  const { type, content, children, style, className, forwardedRef, ...rest } = newProps;
  const styles = Object.assign(types[type] || types.primary, style);

  return (
    <Span ref={forwardedRef} component="span" className={className} style={styles} {...rest}>
      {content || children}
    </Span>
  );
}

Badge.propTypes = {
  children: PropTypes.any.isRequired,
  content: PropTypes.string,
  type: PropTypes.oneOf(Object.keys(types)),
  className: PropTypes.string,
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
};

export default withDeprecated(
  /**
   * @param {BadgeProps} props - Badge组件的属性
   * @param {React.Ref<HTMLSpanElement>} ref - 转发的ref
   * @returns {JSX.Element}
   */
  ({ ref, ...props }) => <Badge {...props} forwardedRef={ref} />,
  { name: 'Badge', alternative: '@arcblock/ux/lib/Tag' }
);

const Span = styled(Typography)`
  && {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    padding: 2px 10px;
    height: 24px;
    line-height: 24px;
  }
`;
