import React from "react";
import classNames from "classnames";
import { Icon } from "../icon";
import { StyledProps } from "../_type";
import { useConfig } from "../_util/config-context";
import { createRocket } from "../_util/create-rocket";
import { forwardRefWithStatics } from "../_util/forward-ref-with-statics";

export interface TagProps extends StyledProps {
  /**
   * 标签内容
   */
  children: React.ReactNode;

  /**
   * 关闭时回调
   *
   * **传递该参数时将展示关闭按钮**
   */
  onClose?: (event: React.MouseEvent) => void;

  /**
   * 颜色主题
   *
   * @default "default"
   */
  theme?: "default" | "primary" | "success" | "warning" | "error";

  /**
   * 是否为深色背景
   *
   * @default false
   */
  dark?: boolean;
}

export const TagGroup = createRocket("TagGroup", "div.@{prefix}-tag-group");

export const Tag = forwardRefWithStatics(
  function Tag(
    { children, onClose, className, theme, dark, ...props }: TagProps,
    ref: React.Ref<HTMLDivElement>
  ) {
    const hasCloseHandler = typeof onClose === "function";
    const { classPrefix } = useConfig();
    const classSuffix = dark ? "-dark" : "";
    return (
      <div
        ref={ref}
        className={classNames(`${classPrefix}-tag`, className, {
          [`${classPrefix}-tag--unlimited-width`]: true,
          [`${classPrefix}-tag--edit`]: hasCloseHandler,
          [`is-blue${classSuffix}`]: theme === "primary",
          [`is-success${classSuffix}`]: theme === "success",
          [`is-warning${classSuffix}`]: theme === "warning",
          // @ts-ignore
          [`is-error${classSuffix}`]: theme === "danger" || theme === "error",
        })}
        {...props}
      >
        <span>{children}</span>
        {hasCloseHandler && <Icon link type="dismiss" onClick={onClose} />}
      </div>
    );
  },
  {
    Group: TagGroup,
  }
);

Tag.displayName = "Tag";
