import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useRef } from 'react';
import clsx from 'clsx';
import { Success } from '@react-vant/icons';
import { addUnit } from '../utils';

const Checker = props => {
  const iconRef = useRef(null);

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

    return null;
  };

  const disabled = useMemo(() => getParentProp('disabled') || props.disabled, [props.parent, props.disabled]);
  const direction = useMemo(() => getParentProp('direction') || null, [props.parent]);
  const iconStyle = useMemo(() => {
    const checkedColor = props.checkedColor || getParentProp('checkedColor');

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

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

  const onClick = event => {
    const {
      target
    } = event;
    const icon = iconRef.current;
    const iconClicked = icon === target || icon.contains(target);

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

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

  const renderIcon = () => {
    const {
      bem,
      shape,
      checked
    } = props;
    const iconSize = props.iconSize || getParentProp('iconSize');
    return _jsx("div", Object.assign({
      ref: iconRef,
      className: clsx(bem('icon', [shape, {
        disabled,
        checked
      }])),
      style: {
        fontSize: addUnit(iconSize)
      }
    }, {
      children: props.iconRender ? props.iconRender({
        checked,
        disabled
      }) : _jsx(Success, {
        style: iconStyle
      })
    }));
  };

  const renderLabel = () => {
    if (props.children) {
      return _jsx("span", Object.assign({
        className: props.bem('label', [props.labelPosition, {
          disabled
        }])
      }, {
        children: props.children
      }));
    }

    return null;
  };

  return _jsxs("div", Object.assign({
    role: props.role,
    className: clsx(props.bem([{
      disabled,
      'label-disabled': props.labelDisabled
    }, direction]), props.className),
    tabIndex: disabled ? -1 : 0,
    "aria-checked": props.checked,
    onClick: onClick
  }, {
    children: [props.labelPosition === 'left' && renderLabel(), renderIcon(), props.labelPosition !== 'left' && renderLabel()]
  }));
};

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