var _excluded = ["items", "checked", "onChange", "children", "buttonProps"];
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
import React, { Children, isValidElement, cloneElement } from "react";
import Flex from "../templates/flex";
import { Button } from "./button";
var getButtonGroupProps = function getButtonGroupProps(itemIndex, itemsLength) {
  var groupFirst = itemIndex == 0;
  var groupLast = itemIndex == itemsLength - 1;
  return {
    groupFirst: groupFirst,
    groupLast: groupLast,
    groupMiddle: !groupFirst && !groupLast
  };
};
var Content = function Content(_ref) {
  var children = _ref.children;
  var renderedChildren = Children.toArray(children).length;
  return /*#__PURE__*/React.createElement(React.Fragment, null, Children.map(children, function (child, index) {
    if (/*#__PURE__*/isValidElement(child)) {
      var buttonGroupProps = getButtonGroupProps(index, renderedChildren);
      return /*#__PURE__*/cloneElement(child, buttonGroupProps);
    }
    return child;
  }));
};
var RadioButtons = function RadioButtons(_ref2) {
  var items = _ref2.items,
    checked = _ref2.checked,
    _ref2$buttonProps = _ref2.buttonProps,
    buttonProps = _ref2$buttonProps === void 0 ? {} : _ref2$buttonProps,
    onChange = _ref2.onChange;
  return /*#__PURE__*/React.createElement(React.Fragment, null, items.map(function (_ref3, index) {
    var label = _ref3.label,
      value = _ref3.value,
      title = _ref3.title;
    var buttonGroupProps = getButtonGroupProps(index, items.length);
    return /*#__PURE__*/React.createElement(Button, _extends({
      key: value,
      label: label,
      onClick: function onClick() {
        return onChange(value);
      }
    }, title ? {
      title: title
    } : {}, checked != value ? {
      flavour: "hollow"
    } : {}, buttonGroupProps, buttonProps));
  }));
};
export var ButtonGroup = function ButtonGroup(_ref4) {
  var items = _ref4.items,
    checked = _ref4.checked,
    onChange = _ref4.onChange,
    children = _ref4.children,
    buttonProps = _ref4.buttonProps,
    props = _objectWithoutPropertiesLoose(_ref4, _excluded);
  return /*#__PURE__*/React.createElement(Flex, _extends({
    alignItems: "center"
  }, props), items != null && items.length ? /*#__PURE__*/React.createElement(RadioButtons, {
    items: items,
    checked: checked,
    onChange: onChange,
    buttonProps: buttonProps
  }) : /*#__PURE__*/React.createElement(Content, null, children));
};