import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["checked", "children", "className", "disabled", "name", "onChange", "onMouseEnter", "onMouseLeave", "label", "size"];
import cx from 'classnames';
import omit from 'lodash.omit';
import React, { useRef } from 'react';
import Box, { omitBoxProps, pickBoxProps } from '../box';
import { TextBodyCompact, TextDisplay, TextSmall } from '../typography';
import theme from './theme.css';

var RadioButton = function RadioButton(_ref) {
  var _cx;

  var _ref$checked = _ref.checked,
      checked = _ref$checked === void 0 ? false : _ref$checked,
      children = _ref.children,
      className = _ref.className,
      _ref$disabled = _ref.disabled,
      disabled = _ref$disabled === void 0 ? false : _ref$disabled,
      name = _ref.name,
      onChange = _ref.onChange,
      onMouseEnter = _ref.onMouseEnter,
      onMouseLeave = _ref.onMouseLeave,
      label = _ref.label,
      _ref$size = _ref.size,
      size = _ref$size === void 0 ? 'medium' : _ref$size,
      others = _objectWithoutProperties(_ref, _excluded);

  var inputNode = useRef(null);
  var TextElement = size === 'small' ? TextSmall : size === 'medium' ? TextBodyCompact : TextDisplay;
  var restProps = omit(others, ['onChange']);
  var boxProps = pickBoxProps(restProps);
  var inputProps = omitBoxProps(restProps);
  var classNames = cx(theme['radiobutton'], theme["is-".concat(size)], (_cx = {}, _defineProperty(_cx, theme['is-checked'], checked), _defineProperty(_cx, theme['is-disabled'], disabled), _cx), className);

  var blur = function blur() {
    if (inputNode.current) {
      inputNode.current.blur();
    }
  };

  var handleToggle = function handleToggle(event) {
    if (event.pageX !== 0 && event.pageY !== 0) {
      blur();
    }

    if (!disabled && onChange) {
      onChange(!checked, event);
    }
  };

  return /*#__PURE__*/React.createElement(Box, _extends({
    element: "label",
    "data-teamleader-ui": "radiobutton",
    className: classNames,
    onMouseEnter: onMouseEnter,
    onMouseLeave: onMouseLeave
  }, boxProps), /*#__PURE__*/React.createElement("input", _extends({
    className: theme['input'],
    type: "radio",
    checked: checked,
    disabled: disabled,
    onClick: handleToggle,
    readOnly: true,
    ref: inputNode,
    name: name
  }, inputProps)), /*#__PURE__*/React.createElement("span", {
    className: theme['shape']
  }), (label || children) && /*#__PURE__*/React.createElement("span", {
    className: theme['label']
  }, label && /*#__PURE__*/React.createElement(TextElement, {
    element: "span",
    color: disabled ? 'neutral' : 'teal'
  }, label), children));
};

export default RadioButton;