import { createVNode as _createVNode, isVNode as _isVNode } from "vue";
import { defineComponent, reactive, watch, provide, getCurrentInstance, toRef } from "vue";
import { filterEmpty, getSlot } from '../_util/props-util';
import Radio from "./Radio";

function _isSlot(s) {
  return typeof s === 'function' || Object.prototype.toString.call(s) === '[object Object]' && !_isVNode(s);
}

export const radioGroupContext = Symbol('radioGroupContext');
export default defineComponent({
  name: 'x-radio-group',
  props: {
    prefixCls: {
      default: 'x-radio-group'
    },
    name: String,
    options: Array,
    value: String,
    vertical: Boolean,
    disabled: Boolean
  },
  emits: ['update:value', 'change'],

  setup(props, {
    emit
  }) {
    const {
      proxy: self
    } = getCurrentInstance();
    const state = reactive({
      value: props.value
    });
    watch(() => props.value, value => [state.value = value]);

    function onChange(e) {
      const val = e.target.value;
      state.value = val;
      emit('update:value', val);
      emit('change', e);
    } // ========================== Provide ==========================


    provide(radioGroupContext, {
      disabledRef: toRef(props, 'disabled'),
      nameRef: toRef(props, 'name'),
      valueRef: toRef(state, 'value'),
      onChange
    });
    return () => {
      var _props$options;

      const {
        prefixCls
      } = props;
      let children;

      if ((_props$options = props.options) !== null && _props$options !== void 0 && _props$options.length) {
        children = props.options.map(opt => {
          if (typeof opt === 'string') {
            return _createVNode(Radio, {
              "key": opt,
              "checked": state.value == opt,
              "name": props.name,
              "value": opt,
              "disabled": props.disabled
            }, _isSlot(opt) ? opt : {
              default: () => [opt]
            });
          } else {
            const val = opt.value,
                  style = opt.style;
            return _createVNode(Radio, {
              "key": val,
              "checked": state.value == val,
              "name": props.name,
              "value": val,
              "disabled": opt.disabled || props.disabled,
              "style": style
            }, {
              default: () => [opt.label]
            });
          }
        });
      } else {
        children = filterEmpty(getSlot(self));
      }

      const cls = [prefixCls, {
        [`${prefixCls}-vertical`]: props.vertical
      }];
      return _createVNode("div", {
        "class": cls
      }, [children]);
    };
  }

});