import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";

/* eslint-disable jsx-a11y/click-events-have-key-events */

/* eslint-disable jsx-a11y/no-static-element-interactions */

/* eslint-disable-next-line jsx-a11y/click-events-have-key-events */
import React from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import findIndex from "lodash-es/findIndex";
import isArray from "lodash-es/isArray";
import isString from "lodash-es/isString";
import remove from "lodash-es/remove";
import Typography from "../Typography";
import getClasses from "./styles";

var ToggleButtonGroup = function ToggleButtonGroup(_ref) {
  var value = _ref.value,
      options = _ref.options,
      exclusive = _ref.exclusive,
      onChange = _ref.onChange;
  var classes = getClasses();

  var isSelected = function isSelected(auxValue) {
    if (exclusive) return auxValue === value;
    if (isArray(value)) return findIndex(value, function (val) {
      return val === auxValue;
    }) >= 0;
    return value === auxValue;
  };

  var handleChange = function handleChange(newValue) {
    return function (event) {
      if (exclusive) onChange(event, newValue);else if (isArray(value)) {
        if (isSelected(newValue)) {
          var auxList = _toConsumableArray(value);

          remove(auxList, function (obj) {
            return obj === newValue;
          });
          onChange(event, auxList);
        } else {
          onChange(event, [].concat(_toConsumableArray(value), [newValue]));
        }
      } else onChange(event, [newValue]);
    };
  };

  return /*#__PURE__*/React.createElement("div", {
    className: classes.root
  }, options.map(function (option, index) {
    return /*#__PURE__*/React.createElement("div", {
      key: "option-".concat(index, "-").concat(option.value),
      onClick: handleChange(option.value),
      className: classnames(classes.option, isSelected(option.value) ? classes.selected : "")
    }, isString(option.label) && /*#__PURE__*/React.createElement(Typography, {
      variant: "h3",
      align: "center"
    }, option.label), !isString(option.label) && option.label);
  }));
};

ToggleButtonGroup.propTypes = {
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool, PropTypes.instanceOf(Array)]),
  options: PropTypes.instanceOf(Array).isRequired,
  exclusive: PropTypes.bool,
  onChange: PropTypes.func
};
ToggleButtonGroup.defaultProps = {
  value: "",
  exclusive: false,
  onChange: function onChange() {}
};
export default ToggleButtonGroup;