import React from "react";
import cn from "classnames";
import PropTypes from "prop-types";

interface IBadgeProps {
  className?: string;
  pill?: boolean;
  variant?: "primary" | "secondary" | "success" | "danger" | "warning" | "info" | "light" | "dark";
  href?: string;
  onClick?: () => void;
  onKeyPress?: () => void;
  tabIndex?: number;
  "data-testid"?: string;
}

const Badge: React.FC<IBadgeProps> = React.forwardRef(
  (
    {
      pill,
      variant,
      className,
      href,
      children,
      "data-testid": dataTestId,
      onClick,
      onKeyPress,
      tabIndex = 0,
      ...props
    },
    ref: React.Ref<HTMLSpanElement>
  ) => {
    const badgeDataTestId = dataTestId || `honeyui-badge-${variant}`;
    const badgeClassName = cn(
      "badge",
      { "badge-pill": pill, [`badge-${variant}`]: variant },
      className
    );

    if (href) {
      return (
        <a
          {...props}
          href={href}
          data-testid={badgeDataTestId}
          className={badgeClassName}
          onClick={onClick}
          onKeyPress={onKeyPress}
          tabIndex={tabIndex}
        >
          {children}
        </a>
      );
    }

    return (
      <span
        {...props}
        data-testid={badgeDataTestId}
        className={cn(badgeClassName, { "cursor-pointer": onClick })}
        onClick={onClick}
        onKeyPress={onKeyPress}
        role="button"
        tabIndex={tabIndex}
        ref={ref}
      >
        {children}
      </span>
    );
  }
);

Badge.displayName = "Badge";
Badge.defaultProps = {
  pill: false,
  tabIndex: 0
};

Badge.propTypes = {
  className: PropTypes.string,
  href: PropTypes.string,
  onClick: PropTypes.func,
  "data-testid": PropTypes.string,
  onKeyPress: PropTypes.func,
  pill: PropTypes.bool,
  tabIndex: PropTypes.number,
  variant: PropTypes.oneOf([
    "primary",
    "secondary",
    "success",
    "danger",
    "warning",
    "info",
    "light",
    "dark",
    null,
    undefined
  ])
};

export default Badge;
