import React, { forwardRef } from "react";
import classNames from "classnames";
import { Tooltip } from "../tooltip";
import { StyledProps } from "../_type";
import { useConfig } from "../_util/config-context";

export interface IconProps
  extends React.HTMLAttributes<HTMLElement>,
    StyledProps {
  /** 图标类型 */
  type: string;

  /**
   * 默认为 16x16 图标
   *
   * 状态图标支持配置为 32x32，包括：`success`、`infowaiting`、`infoblue` 和 `error`
   *
   * @default "default"
   */
  size?: "default" | "s" | "l";

  /**
   * 是否渲染为超链接
   * @default false
   */
  link?: boolean;

  /**
   * 在图标上添加 Tooltip 的快捷方式，详见 [Tooltip](/component/tooltip) 组件
   */
  tooltip?: React.ReactNode;
}

export const Icon = forwardRef(
  (props: IconProps, ref: React.Ref<HTMLElement>) => {
    const { classPrefix } = useConfig();
    const { type = "", size, className, tooltip, link, ...htmlProps } = props;
    const iconClassName = classNames(
      className,
      `${classPrefix}-icon`,
      `${classPrefix}-icon-${type}`,
      {
        "size-s": size === "s",
        "size-l": size === "l",
      }
    );

    const Parent = link ? "a" : "i";

    const label = type.replace("-blue", "").replace("-hover", "");

    const icon = (
      <Parent
        ref={ref as any}
        className={iconClassName}
        role="img"
        aria-label={label}
        {...htmlProps}
      />
    );

    if (tooltip) {
      return <Tooltip title={tooltip}>{icon}</Tooltip>;
    }

    return icon;
  }
);

Icon.displayName = "Icon";
