import { mergeProps as _mergeProps, createVNode as _createVNode } from "vue";
import { defineComponent, computed, getCurrentInstance } from "vue";
import useMemo from '../_util/hooks/useMemo';
import { getComponent } from '../_util/props-util';
const Switch = defineComponent({
  name: 'x-switch',
  props: {
    prefixCls: {
      default: 'x-switch'
    },
    value: [Boolean, Number, String],
    disabled: Boolean,
    checkedChildren: [String, Object],
    unCheckedChildren: [String, Object],
    checkedValue: {
      type: [Boolean, Number, String],
      default: true
    },
    unCheckedValue: {
      type: [Boolean, Number, String],
      default: false
    }
  },
  emits: ['update:value', 'change'],

  setup(props, {
    emit
  }) {
    const {
      proxy: vm
    } = getCurrentInstance();
    const valueRef = useMemo(() => props.value);
    const checkedRef = computed(() => valueRef.value === props.checkedValue);

    function setChecked(checked) {
      if (props.disabled) return;
      valueRef.value = checked ? props.checkedValue : props.unCheckedValue;
      emit('update:value', valueRef.value);
      emit('change', valueRef.value);
    }

    function onClick() {
      setChecked(!checkedRef.value);
    }

    return () => {
      const {
        prefixCls
      } = props;
      const cls = [prefixCls, {
        [`${prefixCls}-checked`]: checkedRef.value,
        [`${prefixCls}-disabled`]: props.disabled
      }];
      const switchProps = {
        class: cls,
        disabled: props.disabled,
        role: 'switch',
        'aria-checked': checkedRef.value
      };
      const node = getComponent(vm, checkedRef.value ? 'checkedChildren' : 'unCheckedChildren');
      const prefixNode = node ? _createVNode("div", {
        "class": `${prefixCls}-text`
      }, [node]) : undefined;
      return _createVNode("button", _mergeProps(switchProps, {
        "type": "button",
        "onClick": onClick
      }), [_createVNode("div", {
        "class": `${prefixCls}_core`
      }, null), prefixNode]);
    };
  }

});

Switch.install = app => {
  app.component(Switch.name, Switch);
};

export default Switch;