import { useEffect } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { useSideDrawerState, useNavigationPages, useRouterPath } from "../../../hooks/election/index.js";
import AutoLayout from "../../layout/AutoLayout/index.js";
import RigPages from './RigPages';
import Battlegrounds from './Battlegrounds';
import LinkSection from './LinkSection';
import CloseButton from './CloseButton';
import useDrawerClickAway from './useDrawerClickAway';
import classes from './styles.module.scss';

/**
 * The side drawer for links to all of our pages as well as recirculation
 * to important elections content.
 */
const SideDrawer = function SideDrawer(props) {
  const {
    battlegroundStates,
    linkSections
  } = props;
  const path = useRouterPath();
  const drawer = useSideDrawerState();
  const pages = useNavigationPages();
  const drawerRef = useDrawerClickAway(drawer);
  useEffect(() => {
    if (drawer.state === 'closed') return undefined;
    const {
      overflow
    } = window.document.body.style;
    window.document.body.style.overflow = 'hidden';
    return () => {
      window.document.body.style.overflow = overflow;
    };
  }, [drawer.state]);
  useEffect(() => () => {
    drawer.close();
  }, [path]);
  const trackingOpts = {
    context: 'SideDrawer'
  };
  return <div className={classnames(classes.container, classes[drawer.state])}>
      <div className={classes.scrim} />

      <div ref={drawerRef} className={classes.drawer}>
        <div className={classes.content}>
          <AutoLayout gap="6" padding={{
          xs: '6',
          md: '8'
        }}>
            <div className={classes.controls}>
              <CloseButton drawer={drawer} tracking={trackingOpts} />
              <RigPages pages={pages} tracking={trackingOpts} />
            </div>

            <Battlegrounds states={battlegroundStates} tracking={trackingOpts} />

            {linkSections.map(section => <LinkSection key={section.title} tracking={trackingOpts} {...section} />)}
          </AutoLayout>
        </div>
      </div>
    </div>;
};
SideDrawer.defaultProps = {
  battlegroundStates: [],
  linkSections: []
};
SideDrawer.propTypes = {
  /**
   * States to highlight as battlegrounds.
   */
  battlegroundStates: PropTypes.arrayOf(PropTypes.string),
  /**
   * Sections of links for recirculation
   */
  linkSections: PropTypes.arrayOf(PropTypes.shape({
    format: PropTypes.oneOf(['standard', 'emphasis']),
    storyCollectionTag: PropTypes.string,
    numberCollectionStories: PropTypes.number,
    title: PropTypes.string.isRequired,
    links: PropTypes.arrayOf(PropTypes.shape({
      label: PropTypes.string.isRequired,
      link: PropTypes.string.isRequired
    }))
  }))
};
export default SideDrawer;