import { jsx as _jsx } from "react/jsx-runtime";
import { 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';

const Swtich = props => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('switch', prefixCls);
  const {
    loading,
    disabled,
    size,
    activeColor,
    inactiveColor
  } = props;
  const [checked, setChecked] = useMergedState({
    value: props.checked,
    defaultValue: props.defaultChecked
  });
  const isChecked = useMemo(() => checked === props.activeValue, [checked, props.activeValue]);
  const style = Object.assign({
    fontSize: addUnit(size),
    backgroundColor: isChecked ? activeColor : inactiveColor
  }, props.style);

  const onClick = e => {
    var _a, _b;

    if (!props.disabled) {
      (_a = props.onClick) === null || _a === void 0 ? void 0 : _a.call(props, e);
    }

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

  const renderLoading = () => {
    if (props.loading) {
      const color = isChecked ? props.activeColor : props.inactiveColor;
      return _jsx(Loading, {
        className: clsx(bem('loading')),
        color: color
      });
    }

    return null;
  };

  return _jsx("div", Object.assign({
    role: "switch",
    tabIndex: 0,
    className: clsx(props.className, bem({
      on: isChecked,
      loading,
      disabled
    })),
    style: style,
    "aria-checked": isChecked,
    onClick: onClick
  }, {
    children: _jsx("div", Object.assign({
      className: clsx(bem('node'))
    }, {
      children: renderLoading()
    }))
  }));
};

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