import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
var _excluded = ["className", "children", "disabled", "name", "required", "value", "onChange", "multiSelect", "wrap"];
import * as React from 'react';
import classNames from 'classnames';
import { ChipContext } from './useChipContext';
import { generateId } from '../utils';
import Flex from '../flex/Flex';

var getGroupValue = function getGroupValue(currentValue, toggledValue, multiSelect) {
  if (multiSelect) {
    if (Array.isArray(currentValue)) {
      return currentValue.includes(toggledValue) ? currentValue.filter(function (v) {
        return v !== toggledValue;
      }) : [].concat(_toConsumableArray(currentValue), [toggledValue]);
    }

    return currentValue === toggledValue ? null : [toggledValue];
  }

  return currentValue === toggledValue ? null : toggledValue;
};

var ChipGroup = function ChipGroup(_ref) {
  var className = _ref.className,
      children = _ref.children,
      disabled = _ref.disabled,
      name = _ref.name,
      required = _ref.required,
      value = _ref.value,
      onChange = _ref.onChange,
      multiSelect = _ref.multiSelect,
      _ref$wrap = _ref.wrap,
      wrap = _ref$wrap === void 0 ? true : _ref$wrap,
      props = _objectWithoutProperties(_ref, _excluded);

  var chipGroupClass = classNames('sg-chip-group', className);
  var groupRole = multiSelect ? 'group' : 'radiogroup';

  var _React$useRef = React.useRef(name || "ChipGroup_".concat(generateId())),
      groupName = _React$useRef.current;

  var _React$useState = React.useState(value || null),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      selectedValue = _React$useState2[0],
      setSelectedValue = _React$useState2[1];

  React.useEffect(function () {
    setSelectedValue(value);
  }, [value]);

  var setValue = function setValue(event, chipValue) {
    setSelectedValue(getGroupValue(selectedValue, chipValue, multiSelect));
    if (onChange) onChange(event, chipValue);
  };

  return /*#__PURE__*/React.createElement(Flex, _extends({
    gap: "s",
    className: chipGroupClass,
    role: groupRole,
    "aria-disabled": disabled,
    wrap: wrap
  }, props), /*#__PURE__*/React.createElement(ChipContext.Provider, {
    value: {
      name: groupName,
      disabled: disabled,
      required: required,
      groupValue: selectedValue,
      multiSelect: multiSelect,
      onChipChange: setValue
    }
  }, children));
};

export default ChipGroup;