import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useContext, useMemo } from 'react';
import cls from 'clsx';
import useMergedState from '../hooks/use-merged-state';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
import SidebarItem from './SidebarItem';

const Sidebar = _a => {
  var {
    children,
    className,
    style
  } = _a,
      props = __rest(_a, ["children", "className", "style"]);

  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('sidebar', prefixCls);
  const [active, updateActive] = useMergedState({
    value: props.value,
    defaultValue: props.defaultValue
  });

  const getActive = () => active;

  const setActive = value => {
    var _a;

    if (value !== getActive()) {
      updateActive(value);
      (_a = props.onChange) === null || _a === void 0 ? void 0 : _a.call(props, value);
    }
  };

  const validChildren = useMemo(() => React.Children.toArray(children).filter(Boolean).map(child => {
    if (!React.isValidElement(child)) return null;

    if (child.type !== SidebarItem) {
      if (process.env.NODE_ENV !== 'production') {
        // eslint-disable-next-line no-console
        console.error('[React Vant] <SidebarItem> must be a child component of <Sidebar>.');
      }

      return null;
    }

    return child;
  }), [children]);
  return _jsxs("div", Object.assign({
    className: cls(className, bem('wrapper')),
    style: style
  }, {
    children: [_jsx("div", Object.assign({
      className: cls(props.sideClassName, bem()),
      style: props.sideStyle
    }, {
      children: validChildren.map((child, index) => React.cloneElement(child, {
        index,
        parent: {
          setActive,
          getActive
        }
      }))
    })), validChildren.map((child, index) => {
      return _jsx("div", Object.assign({
        className: cls(child.props.contentClassName, bem('content')),
        style: Object.assign(Object.assign({}, child.props.contentStyle), {
          display: index === getActive() ? undefined : 'none'
        })
      }, {
        children: child.props.children
      }), child.key);
    })]
  }));
};

Sidebar.defaultProps = {
  defaultValue: 0
};
export default Sidebar;