import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["children", "className", "selectedIndex", "small", "onChange"];
import PropTypes from 'prop-types';
import React, { useState } from 'react';
import classNames from 'classnames';
import { settings } from '../../globals/js';
var prefix = settings.prefix;
/** ContentSwitcher manipulates the content shown following an exclusive or “either/or” pattern. It is used to toggle between two or more content sections within the same space on screen. Only one section can be shown at a time.
 */

export default function ContentSwitcher(_ref) {
  var children = _ref.children,
      className = _ref.className,
      selectedIndex = _ref.selectedIndex,
      small = _ref.small,
      onChange = _ref.onChange,
      other = _objectWithoutProperties(_ref, _excluded);

  var _useState = useState(selectedIndex),
      _useState2 = _slicedToArray(_useState, 2),
      selectedIdx = _useState2[0],
      setSelectedIndex = _useState2[1];

  var getChildren = function getChildren(children) {
    return React.Children.map(children, function (child, index) {
      return /*#__PURE__*/React.cloneElement(child, {
        index: index,
        onClick: handleChildChange,
        onKeyDown: handleChildChange,
        selected: index === selectedIdx
      });
    });
  };

  var handleChildChange = function handleChildChange(data) {
    var index = data.index;

    if (selectedIdx !== index) {
      setSelectedIndex(index);
      onChange(data);
    }
  };

  var classes = classNames("".concat(prefix, "--content-switcher"), className, _defineProperty({}, "".concat(prefix, "--content-switcher--sm"), small));
  return /*#__PURE__*/React.createElement("div", _extends({}, other, {
    className: classes
  }), getChildren(children));
}
ContentSwitcher.propTypes = {
  /** Specify the content of your ContentSwitcher */
  children: PropTypes.node,

  /** Specify an optional className to be added to your ContentSwitcher */
  className: PropTypes.string,

  /** Specify an `onChange` handler that is called whenever the ContentSwitcher changes which item is selected */
  onChange: PropTypes.func.isRequired,

  /** Specify a selected index for the initially selected content */
  selectedIndex: PropTypes.number
};
ContentSwitcher.defaultProps = {
  selectedIndex: 0
};