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", "disabled", "maxLines", "className", "label", "onChange", "size"];
import cx from 'classnames';
import React, { useRef } from 'react';
import Box, { omitBoxProps, pickBoxProps } from '../box';
import { TextBodyCompact, TextDisplay, TextSmall } from '../typography';
import theme from './theme.css';

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

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

  var ref = useRef(null);
  var boxProps = pickBoxProps(others);
  var inputProps = omitBoxProps(others);

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

  var handleToggle = function handleToggle(event) {
    blur();

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

  var classNames = cx(theme['toggle'], theme["is-".concat(size)], (_cx = {}, _defineProperty(_cx, theme['is-checked'], checked), _defineProperty(_cx, theme['is-disabled'], disabled), _cx), className);
  var TextElement = size === 'small' ? TextSmall : size === 'medium' ? TextBodyCompact : TextDisplay;
  return /*#__PURE__*/React.createElement(Box, _extends({
    element: "label",
    "data-teamleader-ui": "toggle",
    className: classNames
  }, boxProps), /*#__PURE__*/React.createElement("input", _extends({
    className: theme['input'],
    type: "checkbox",
    hidden: true,
    checked: checked,
    disabled: disabled,
    onChange: handleToggle,
    ref: ref
  }, inputProps)), /*#__PURE__*/React.createElement("span", {
    className: theme['track']
  }, /*#__PURE__*/React.createElement("span", {
    className: theme['thumb']
  })), (label || children) && /*#__PURE__*/React.createElement("span", {
    className: theme['label']
  }, label && /*#__PURE__*/React.createElement(TextElement, {
    element: "span",
    color: disabled ? 'neutral' : 'teal',
    maxLines: maxLines
  }, label), children));
};

export default Toggle;