import React from "react";
import classNames from "classnames";
import { ControlledProps, useDefaultValue } from "../form/controlled";
import { StyledProps } from "../_type";
import { Button } from "../button";
import { SegmentOption } from "./SegmentOption";
import { Bubble } from "../bubble";
import { useConfig } from "../_util/config-context";
import { SegmentGroup, SegmentGroupItem } from "./SegmentGroup";
import { forwardRefWithStatics } from "../_util/forward-ref-with-statics";
import { mergeEventProps } from "../_util/merge-event-props";

export interface SegmentProps extends ControlledProps<string>, StyledProps {
  /**
   * Segment 中选项
   */
  options: SegmentOption[];

  /**
   * 分组
   */
  groups?: {
    [groupKey: string]: React.ReactNode;
  };

  /**
   * 是否禁用所有选择
   * @default false
   * @since 2.2.0
   */
  disabled?: boolean;

  /**
   * 是否为无边框样式
   * @default false
   */
  rimless?: boolean;

  /**
   * 包含分组时，外层分组容器自定义类名
   */
  groupClassName?: string;

  /**
   * 包含分组时，外层分组容器自定义样式
   */
  groupStyle?: React.CSSProperties;
}

export const Segment = forwardRefWithStatics(
  function Segment(props: SegmentProps, ref: React.Ref<HTMLDivElement>) {
    const {
      value,
      onChange,
      options,
      groups,
      groupClassName,
      groupStyle,
    } = useDefaultValue(props, "");
    if (groups) {
      return (
        <SegmentGroup ref={ref} className={groupClassName} style={groupStyle}>
          {Object.entries(groups).map(([key, name]) => {
            const subOptions = options.filter(i => i.groupKey === key);
            return (
              <SegmentGroupItem name={name} key={key}>
                <SegmentMain
                  {...props}
                  options={subOptions}
                  value={value}
                  onChange={onChange}
                />
              </SegmentGroupItem>
            );
          })}
        </SegmentGroup>
      );
    }
    return (
      <SegmentMain ref={ref} {...props} value={value} onChange={onChange} />
    );
  },
  {
    defaultLabelAlign: "middle",
  }
);

Segment.displayName = "Segment";

const SegmentMain = React.forwardRef(function SegmentMain(
  {
    value,
    onChange,
    options,
    disabled,
    rimless,
    className,
    style,
    ...props
  }: SegmentProps,
  ref: React.Ref<HTMLDivElement>
) {
  const { classPrefix } = useConfig();
  return (
    <div
      ref={ref}
      className={classNames(`${classPrefix}-segment`, className, {
        [`${classPrefix}-segment--rimless`]: rimless,
      })}
      style={style}
      {...mergeEventProps(props)}
    >
      {options.map(option => {
        const button = (
          <Button
            key={option.value}
            disabled={disabled || option.disabled}
            tooltip={option.tooltip}
            htmlType="button"
            className={classNames(option.className, {
              "is-selected": option.value === value,
            })}
            onClick={
              disabled || option.disabled
                ? null
                : event => {
                    onChange(option.value, { event });
                  }
            }
            style={option.style}
            role="radio"
            aria-checked={option.value === value}
          >
            {option.text || option.value}
          </Button>
        );
        if (option.bubble) {
          return (
            <Bubble key={option.value} content={option.bubble}>
              {button}
            </Bubble>
          );
        }
        return button;
      })}
    </div>
  );
});

SegmentMain.displayName = "SegmentMain";
