"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var React = _interopRequireWildcard(require("react"));

var _bem = require("@zarm-design/bem");

var _configProvider = require("../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 = (0, _objectWithoutProperties2.default)(props, ["className", "style", "disabled", "checked", "defaultChecked", "onChange"]);
  var getChecked = checked || defaultChecked || false;

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

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

  var bem = (0, _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", (0, _extends2.default)({}, 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
};
var _default = Switch;
exports.default = _default;