import { useCallback } from 'react';
import PropTypes from 'prop-types';
import ElectionToggle from "../../ElectionToggle/index.jsx";
import useUrlState from "../../../../hooks/useUrlState/index.js";
const Toggle = function Toggle(props) {
  const {
    node,
    components,
    LayoutNode
  } = props;
  const urlState = useUrlState({
    stateMode: 'hash'
  });
  const {
    nodes
  } = node;
  const tabs = nodes.map(tab => ({
    id: tab.id,
    label: tab.label
  }));
  const {
    tab
  } = urlState.data;
  const activeTabIndex = nodes.findIndex(n => !tab || tab === n.label);
  const setActiveTabIndex = useCallback(i => {
    const newTab = nodes[i];
    urlState.set('tab', newTab.label);
  }, [urlState.set]);
  const activeTab = nodes[activeTabIndex];
  return <div>
      <ElectionToggle tabs={tabs} activeTabIndex={activeTabIndex} setActiveTabIndex={setActiveTabIndex} />
      {activeTab.nodes.map(childNode => <LayoutNode key={childNode.id} node={childNode} components={components} />)}
    </div>;
};
Toggle.defaultProps = {
  components: undefined
};
Toggle.propTypes = {
  node: PropTypes.shape({
    nodes: PropTypes.arrayOf(PropTypes.shape({
      id: PropTypes.string.isRequired,
      label: PropTypes.string.isRequired,
      nodes: PropTypes.arrayOf(PropTypes.shape({
        id: PropTypes.string.isRequired
      }))
    })).isRequired
  }).isRequired,
  components: PropTypes.shape({}),
  LayoutNode: PropTypes.elementType.isRequired
};
export default Toggle;