import React, { forwardRef, Ref } from "react";
import classNames from "classnames";
import warning from "warning";
import { StyledProps } from "../_type";
import { Button } from "../button";
import { useConfig } from "../_util/config-context";

export interface ButtonBarItem {
  /* 文案 */
  name: string | JSX.Element;

  /* 值 */
  value: number | string;

  /* 图标 */
  icon?: string | JSX.Element;

  /* 是否可用 */
  disabled?: boolean;

  /* 提示 */
  tip?: string;
}

export interface ButtonBarProps extends StyledProps {
  /* 列表数据 */
  list: ButtonBarItem[];

  /* 选中的按钮 */
  selected?: ButtonBarItem | number | string;

  /* 选择后的回调 */
  onSelect?: (value: ButtonBarItem) => void;
}

export const ButtonBar = forwardRef(
  (props: ButtonBarProps, ref: Ref<HTMLDivElement>) => {
    const { list, onSelect, className, style } = props;
    let { selected } = props;

    const { classPrefix } = useConfig();

    // 统一成标量，方便对比
    if (selected && typeof selected === "object") {
      selected = selected.value;
    }
    warning(false, "ButtonBar 组件已废弃，请改用 Segment");
    return (
      <div
        ref={ref}
        className={classNames(`${classPrefix}-segment`, className)}
        style={style}
      >
        {list.map((item, index) => (
          <Button
            key={index}
            type="primary"
            title={item.tip}
            className={classNames({
              "is-selected": selected && item.value === selected,
            })}
            disabled={item.disabled}
            onClick={item.disabled ? null : () => onSelect(item)}
          >
            {item.name}
            {item.icon}
          </Button>
        ))}
      </div>
    );
  }
);

ButtonBar.displayName = "ButtonBar";
