import _extends from "@babel/runtime/helpers/extends";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import * as React from 'react';
import { createBEM } from '@zarm-design/bem';
import { ConfigContext } from '../config-provider';
var Switch = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var className = props.className,
      style = props.style,
      disabled = props.disabled,
      checked = props.checked,
      defaultChecked = props.defaultChecked,
      onChange = props.onChange,
      restProps = _objectWithoutProperties(props, ["className", "style", "disabled", "checked", "defaultChecked", "onChange"]);

  var getChecked = checked || defaultChecked || false;

  var _React$useState = React.useState(getChecked),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      currentChecked = _React$useState2[0],
      setCurrentChecked = _React$useState2[1];

  var _React$useContext = React.useContext(ConfigContext),
      prefixCls = _React$useContext.prefixCls;

  var bem = createBEM('switch', {
    prefixCls: prefixCls
  });
  var cls = bem([{
    disabled: disabled
  }, className]);

  var onInputChange = function onInputChange() {
    var newChecked = !currentChecked;

    if (!('checked' in props)) {
      setCurrentChecked(newChecked);
    }

    onChange === null || onChange === void 0 ? void 0 : onChange(newChecked);
  };

  React.useEffect(function () {
    setCurrentChecked(getChecked);
  }, [getChecked]);
  return /*#__PURE__*/React.createElement("span", {
    className: cls,
    style: style,
    ref: ref
  }, /*#__PURE__*/React.createElement("input", _extends({}, restProps, {
    role: "switch",
    "aria-checked": currentChecked,
    type: "checkbox",
    className: bem('input'),
    disabled: disabled,
    value: currentChecked ? 'on' : 'off',
    checked: 'checked' in props ? currentChecked : undefined,
    defaultChecked: 'defaultChecked' in props ? defaultChecked : undefined,
    onChange: 'onChange' in props ? onInputChange : undefined
  })));
});
Switch.displayName = 'Switch';
Switch.defaultProps = {
  disabled: false
};
export default Switch;