import React, { forwardRef, Ref } from "react";
import classNames from "classnames";
import { Placement } from "popper.js";
import { useConfig } from "../_util/config-context";
import { StyledProps } from "../_type";

export interface BubbleContentProps
  extends StyledProps,
    React.HTMLAttributes<HTMLDivElement> {
  /**
   * Bubble 放置的位置，将影响三角的朝向和位置
   * @default "top"
   */
  placement?: Placement;

  /**
   * 指定 `error = true` 则渲染为红色，指示错误内容
   * @default false
   */
  error?: boolean;

  /**
   * 指定 `dark = true` 则渲染为黑色
   * @default false
   */
  dark?: boolean;

  /**
   * 指定 `tooltip = true` 则渲染为 Tooltip 样式
   * @default false
   */
  tooltip?: boolean;

  /**
   * 气泡内容
   */
  children?: React.ReactNode;
}

// 三角朝向和 placement 位置是相对的
const POSITION_MAP = {
  top: "bottom",
  bottom: "top",
  left: "right",
  right: "left",
};

export const BubbleContent = forwardRef(
  (props: BubbleContentProps, ref: Ref<HTMLDivElement>) => {
    const {
      placement = "top",
      children,
      className,
      error,
      dark,
      tooltip,
      ...htmlProps
    } = props;

    const { classPrefix } = useConfig();

    // placement 可能是 "top-start" 的形式，需要拆成两个词来使用
    let [basePlacement, placementModifier] = placement.split("-"); // eslint-disable-line prefer-const

    if (basePlacement === "auto") {
      basePlacement = "top";
    }

    const focusPosition = POSITION_MAP[basePlacement] || "bottom";

    if (tooltip) {
      return (
        <div className={`${classPrefix}-tooltip`} ref={ref} {...htmlProps}>
          <div className={`${classPrefix}-tooltip__inner`}>{children}</div>
        </div>
      );
    }

    return (
      <div
        ref={ref}
        className={classNames({
          [`${classPrefix}-bubble`]: true,
          [`${classPrefix}-bubble--${focusPosition}`]: focusPosition,
          [`${classPrefix}-bubble--${placementModifier}`]: placementModifier,
          [`${classPrefix}-bubble--error`]: error,
          [`${classPrefix}-bubble--reverse`]: dark,
          [className]: className,
        })}
        {...htmlProps}
      >
        <div className={`${classPrefix}-bubble__inner`}>{children}</div>
      </div>
    );
  }
);

BubbleContent.displayName = "BubbleContent";
