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

export interface InputAdornmentProps extends StyledProps {
  /**
   * 前缀装饰
   */
  before?: React.ReactNode;

  /**
   * 后缀装饰
   */
  after?: React.ReactNode;

  /**
   * 被装饰内容
   */
  children?: React.ReactNode;

  /**
   * 展示类型
   * @default “default”
   */
  appearance?: "default" | "pure";

  /**
   * **\[Deprecated\]** 请使用 `appearance` 属性
   * @deprecated
   */
  appearence?: "default" | "pure";
}

const wrapAdornmentAddon = (addon: React.ReactNode, classPrefix: string) => (
  <div className={`${classPrefix}-input-group__addon`}>{addon}</div>
);

const wrapAdornmentText = (
  text: string,
  pure: boolean,
  classPrefix: string
) => (
  <span
    className={
      pure
        ? `${classPrefix}-form__help-text--inline`
        : `${classPrefix}-input-group__text`
    }
  >
    {text}
  </span>
);

export const InputAdornment = forwardRefWithStatics(
  function InputAdornment(
    {
      before,
      after,
      children,
      appearence,
      appearance = appearence,
      className,
      ...props
    }: InputAdornmentProps,
    ref: React.Ref<HTMLDivElement>
  ) {
    const { classPrefix } = useConfig();
    if (typeof before === "string") {
      // eslint-disable-next-line no-param-reassign
      before = wrapAdornmentText(before, false, classPrefix);
    }
    if (typeof after === "string") {
      // eslint-disable-next-line no-param-reassign
      after = wrapAdornmentText(after, appearance === "pure", classPrefix);
    }

    return (
      <div
        ref={ref}
        className={classNames(`${classPrefix}-input-group`, className)}
        {...props}
      >
        {before && wrapAdornmentAddon(before, classPrefix)}
        {children}
        {after && wrapAdornmentAddon(after, classPrefix)}
      </div>
    );
  },
  {
    defaultLabelAlign: "middle",
  }
);

InputAdornment.displayName = "InputAdornment";

/**
 * @deprecated
 *
 * 请使用 InputAdornment 代替
 */
export const InputAdorment = InputAdornment;
