import React, { useMemo, useRef } from 'react';
import clsx from 'clsx';
import { Success } from '@react-vant/icons';
import { addUnit } from '../utils';

var Checker = function Checker(props) {
  var iconRef = useRef(null);

  var getParentProp = function getParentProp(name) {
    if (props.parent && props.bindGroup) {
      return props.parent.props[name];
    }

    return null;
  };

  var disabled = useMemo(function () {
    return getParentProp('disabled') || props.disabled;
  }, [props.parent, props.disabled]);
  var direction = useMemo(function () {
    return getParentProp('direction') || null;
  }, [props.parent]);
  var iconStyle = useMemo(function () {
    var checkedColor = props.checkedColor || getParentProp('checkedColor');

    if (checkedColor && props.checked && !disabled) {
      return {
        borderColor: checkedColor,
        backgroundColor: checkedColor
      };
    }

    return {};
  }, [props.checkedColor, props.checked, disabled]);

  var onClick = function onClick(event) {
    var target = event.target;
    var icon = iconRef.current;
    var iconClicked = icon === target || icon.contains(target);

    if (!disabled && (iconClicked || !props.labelDisabled)) {
      if (props.onToggle) {
        props.onToggle();
      }
    }

    if (props.onClick) {
      props.onClick(event);
    }
  };

  var renderIcon = function renderIcon() {
    var bem = props.bem,
        shape = props.shape,
        checked = props.checked;
    var iconSize = props.iconSize || getParentProp('iconSize');
    return /*#__PURE__*/React.createElement("div", {
      ref: iconRef,
      className: clsx(bem('icon', [shape, {
        disabled: disabled,
        checked: checked
      }])),
      style: {
        fontSize: addUnit(iconSize)
      }
    }, props.iconRender ? props.iconRender({
      checked: checked,
      disabled: disabled
    }) : /*#__PURE__*/React.createElement(Success, {
      style: iconStyle
    }));
  };

  var renderLabel = function renderLabel() {
    if (props.children) {
      return /*#__PURE__*/React.createElement("span", {
        className: props.bem('label', [props.labelPosition, {
          disabled: disabled
        }])
      }, props.children);
    }

    return null;
  };

  return /*#__PURE__*/React.createElement("div", {
    role: props.role,
    className: clsx(props.bem([{
      disabled: disabled,
      'label-disabled': props.labelDisabled
    }, direction]), props.className),
    tabIndex: disabled ? -1 : 0,
    "aria-checked": props.checked,
    onClick: onClick
  }, props.labelPosition === 'left' && renderLabel(), renderIcon(), props.labelPosition !== 'left' && renderLabel());
};

Checker.defaultProps = {
  shape: 'round',
  bindGroup: true
};
export default Checker;