import _extends from "@babel/runtime/helpers/extends";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import { createBEM } from '@zarm-design/bem';
import React, { cloneElement, useCallback, useState } from 'react';
import { ConfigContext } from '../config-provider';
var TabBar = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var _React$useContext = React.useContext(ConfigContext),
      prefixCls = _React$useContext.prefixCls;

  var bem = createBEM('tab-bar', {
    prefixCls: prefixCls
  });

  var className = props.className,
      children = props.children,
      onChange = props.onChange,
      activeKey = props.activeKey,
      defaultActiveKey = props.defaultActiveKey,
      rest = _objectWithoutProperties(props, ["className", "children", "onChange", "activeKey", "defaultActiveKey"]);

  var _useState = useState(defaultActiveKey),
      _useState2 = _slicedToArray(_useState, 2),
      selectedKey = _useState2[0],
      setSelectedKey = _useState2[1];

  var onChildChange = useCallback(function (value) {
    if (!activeKey) {
      setSelectedKey(value);
    }

    onChange === null || onChange === void 0 ? void 0 : onChange(value);
  }, [activeKey, onChange]);

  var getSelected = function getSelected(index, itemKey) {
    if (!activeKey) {
      if (!defaultActiveKey && index === 0) {
        return true;
      }

      return defaultActiveKey === itemKey;
    }

    return activeKey === itemKey;
  };

  var items = React.Children.map(children, function (element, index) {
    if (! /*#__PURE__*/React.isValidElement(element)) return null;
    var itemKey = element.props.itemKey || index;
    var selected = getSelected(index, itemKey);

    if (!activeKey) {
      selected = selectedKey === itemKey;

      if (!selectedKey && index === 0) {
        selected = true;
      }
    }

    return /*#__PURE__*/cloneElement(element, {
      key: index,
      // disabled: element.props.disabled,
      onClick: function onClick() {
        return onChildChange(itemKey);
      },
      badge: element.props.badge,
      title: element.props.title,
      icon: element.props.icon,
      itemKey: itemKey,
      style: element.props.style,
      selected: selected
    });
  });
  return /*#__PURE__*/React.createElement("div", _extends({}, rest, {
    ref: ref,
    className: bem([className])
  }), /*#__PURE__*/React.createElement("div", {
    className: bem('wrapper')
  }, items));
});
TabBar.displayName = 'TabBar';
export default TabBar;