function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

import React, { useContext, useMemo } from 'react';
import clsx from 'clsx';
import useMergedState from '../hooks/use-merged-state';
import Loading from '../loading';
import { addUnit } from '../utils';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';

var Swtich = function Swtich(props) {
  var _useContext = useContext(ConfigProviderContext),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('switch', prefixCls),
      bem = _createNamespace[0];

  var loading = props.loading,
      disabled = props.disabled,
      size = props.size,
      activeColor = props.activeColor,
      inactiveColor = props.inactiveColor;

  var _useMergedState = useMergedState({
    value: props.checked,
    defaultValue: props.defaultChecked
  }),
      checked = _useMergedState[0],
      setChecked = _useMergedState[1];

  var isChecked = useMemo(function () {
    return checked === props.activeValue;
  }, [checked, props.activeValue]);

  var style = _extends({
    fontSize: addUnit(size),
    backgroundColor: isChecked ? activeColor : inactiveColor
  }, props.style);

  var onClick = function onClick(e) {
    if (!props.disabled) {
      props.onClick == null ? void 0 : props.onClick(e);
    }

    if (!props.disabled && !props.loading) {
      var newValue = isChecked ? props.inactiveValue : props.activeValue;
      setChecked(newValue);
      props.onChange == null ? void 0 : props.onChange(newValue);
    }
  };

  var renderLoading = function renderLoading() {
    if (props.loading) {
      var color = isChecked ? props.activeColor : props.inactiveColor;
      return /*#__PURE__*/React.createElement(Loading, {
        className: clsx(bem('loading')),
        color: color
      });
    }

    return null;
  };

  return /*#__PURE__*/React.createElement("div", {
    role: "switch",
    tabIndex: 0,
    className: clsx(props.className, bem({
      on: isChecked,
      loading: loading,
      disabled: disabled
    })),
    style: style,
    "aria-checked": isChecked,
    onClick: onClick
  }, /*#__PURE__*/React.createElement("div", {
    className: clsx(bem('node'))
  }, renderLoading()));
};

Swtich.defaultProps = {
  activeValue: true,
  inactiveValue: false
};
export default Swtich;