import React from "react";
import classNames from "classnames";
import { Icon } from "../icon";
import { Text } from "../text";
import { useTranslation } from "../i18n";
import { StyledProps } from "../_type";
import { useConfig } from "../_util/config-context";

export interface ErrorTipProps extends StyledProps {
  /**
   * 错误文案
   * @default "加载失败"
   */
  errorText?: React.ReactNode;

  /**
   * 重试文案
   * @default "重试"
   */
  retryText?: React.ReactNode;

  /**
   * 重试时回调，如果传空，则不进行重试
   */
  onRetry?: () => void;

  /**
   * 隐藏图标
   * @default false
   */
  hideIcon?: boolean;
}

export const ErrorTip = React.forwardRef(function ErrorTip(
  props: ErrorTipProps,
  ref: React.Ref<HTMLSpanElement>
) {
  const { classPrefix } = useConfig();
  const t = useTranslation();
  const {
    errorText = t.loadErrorText,
    retryText = t.loadRetryText,
    onRetry,
    hideIcon,
    className,
    ...restProps
  } = props;
  return (
    <span
      ref={ref}
      className={classNames(`${classPrefix}-action-state`, className)}
      {...restProps}
    >
      {!hideIcon && <Icon type="error" className={`${classPrefix}-mr-2n`} />}
      {typeof errorText === "string" ? (
        <Text
          className={`${classPrefix}-action-state__text`}
          theme="danger"
          title={errorText}
        >
          {errorText}
        </Text>
      ) : (
        errorText
      )}
      {onRetry && (
        <>
          {" "}
          <a
            className={`${classPrefix}-action-state__text ${classPrefix}-ml-1n`}
            onClick={onRetry}
          >
            {retryText}
          </a>
        </>
      )}
    </span>
  );
});

ErrorTip.displayName = "ErrorTip";
