import React from "react";
import classNames from "classnames";
import { ControlledProps, useDefaultValue } from "../form/controlled";
import { CheckContext, CheckContextValue, CheckChangeContext } from "../check";
import { StyledProps } from "../_type";
import { useConfig } from "../_util/config-context";

/**
 * RadioGroup 组件所接收的属性
 */
export interface RadioGroupProps extends ControlledProps<string>, StyledProps {
  /**
   * 当前选中的 Radio 的 name
   */
  value?: string;

  /**
   * 值变更时回调
   */
  onChange?: (value: string, context: CheckChangeContext) => void;

  /**
   * 禁用组件
   * @default false
   */
  disabled?: boolean;

  /**
   * 使用水平布局（inline）还是纵向排列布局（column）
   * @default "inline"
   */
  layout?: "inline" | "column";

  /**
   * 单选按钮内容
   */
  children?: React.ReactNode;
}

export interface RadioGroupTarget {
  /** 当前选中的 Radio 的值 */
  value: string;
}

/**
 * 单选选项组，里面可以嵌套 <Radio />
 */
export function RadioGroup(props: RadioGroupProps) {
  const { classPrefix } = useConfig();
  const {
    disabled,
    layout,
    children,
    value,
    onChange,
    className,
    style,
  } = useDefaultValue(props);

  const context: CheckContextValue = {
    inject: checkProps => {
      // 只为 radio 提供
      if (checkProps.type !== "radio") {
        return checkProps;
      }
      // 如果已经受控，则不注入
      if (typeof checkProps.value === "boolean") {
        return checkProps;
      }

      const checkName = checkProps.name;
      if (typeof checkName === "undefined") {
        console.warn(
          '<Radio> managed by <RadioGroup> must include the "name" prop'
        );
        return checkProps;
      }

      return {
        ...checkProps,
        value: value === checkProps.name,
        disabled: checkProps.disabled || disabled,
        display: layout === "column" ? "block" : "inline",
        onChange(checked, context) {
          if (typeof checkProps.onChange === "function") {
            checkProps.onChange(checked, context);
            if (context.event.defaultPrevented) {
              return;
            }
          }
          if (typeof onChange === "function") {
            onChange(checkName, context);
          }
        },
      };
    },
  };

  return (
    <div
      className={classNames(`${classPrefix}-form-check-group`, className)}
      style={style}
    >
      <CheckContext.Provider value={context}>{children}</CheckContext.Provider>
    </div>
  );
}
