import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { useClassNames, useControlled, useCustom } from '../utils';
import Plaintext from '../Plaintext';
var defaultProps = {
  as: 'span',
  classPrefix: 'btn-toggle'
};
var Toggle = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var Component = props.as,
      disabled = props.disabled,
      readOnly = props.readOnly,
      plaintext = props.plaintext,
      className = props.className,
      checkedChildren = props.checkedChildren,
      unCheckedChildren = props.unCheckedChildren,
      classPrefix = props.classPrefix,
      checkedProp = props.checked,
      defaultChecked = props.defaultChecked,
      size = props.size,
      localeProp = props.locale,
      onChange = props.onChange,
      rest = _objectWithoutPropertiesLoose(props, ["as", "disabled", "readOnly", "plaintext", "className", "checkedChildren", "unCheckedChildren", "classPrefix", "checked", "defaultChecked", "size", "locale", "onChange"]);

  var _useControlled = useControlled(checkedProp, defaultChecked),
      checked = _useControlled[0],
      setChecked = _useControlled[1];

  var _useCustom = useCustom('Toggle', localeProp),
      locale = _useCustom.locale;

  var _useClassNames = useClassNames(classPrefix),
      merge = _useClassNames.merge,
      withClassPrefix = _useClassNames.withClassPrefix,
      prefix = _useClassNames.prefix;

  var classes = merge(className, withClassPrefix(size, {
    checked: checked,
    disabled: disabled
  }));
  var inner = checked ? checkedChildren : unCheckedChildren;
  var label = checked ? locale.on : locale.off;
  var handleChange = useCallback(function (event) {
    if (disabled || readOnly) {
      return;
    }

    setChecked(!checked);
    onChange === null || onChange === void 0 ? void 0 : onChange(!checked, event);
  }, [checked, disabled, onChange, readOnly, setChecked]);

  if (plaintext) {
    return /*#__PURE__*/React.createElement(Plaintext, null, inner || label);
  }

  return /*#__PURE__*/React.createElement(Component, _extends({
    role: "switch",
    "aria-checked": checked,
    "aria-disabled": disabled,
    "aria-label": typeof inner === 'string' ? inner : label,
    tabIndex: -1
  }, rest, {
    ref: ref,
    className: classes,
    onClick: handleChange
  }), /*#__PURE__*/React.createElement("span", {
    className: prefix('inner')
  }, inner));
});
Toggle.displayName = 'Toggle';
Toggle.defaultProps = defaultProps;
Toggle.propTypes = {
  disabled: PropTypes.bool,
  checked: PropTypes.bool,
  defaultChecked: PropTypes.bool,
  checkedChildren: PropTypes.node,
  unCheckedChildren: PropTypes.node,
  classPrefix: PropTypes.string,
  className: PropTypes.string,
  onChange: PropTypes.func
};
export default Toggle;