import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import 'reset-css/reset.css';
import '../color/color';
import '../grid/grid';
import '../media-queries/media-queries';
import '../typography/typography';
import css from './navigation-list.css';
import { keyCodes } from '../../constants';

const NavigationControl = ({
  title,
  children,
  type,
  menuIsOpen,
  showNavToggle,
  listIsOpen,
  hideOnDesktop,
}) => {
  const [listVisible, setListVisible] = useState();

  useEffect(() => {
    // Close the list everytime the user closes the menu.
    if (!menuIsOpen && !listIsOpen) {
      setListVisible(false);
    }
    if (listIsOpen) {
      setListVisible(true);
    }
  }, [menuIsOpen]);

  function toggle(e) {
    e.preventDefault();
    setListVisible(!listVisible);
  }

  // Call toggle() when enter key (13) or spacebar key (32) is pressed
  function keyDown(e) {
    if ([keyCodes.ENTER, keyCodes.SPACE].includes(e.keyCode)) {
      toggle(e);
    }
  }

  return (
    <li
      className={classnames([
        css['ds-navigation-list'],
        css[`ds-navigation-list--${type}`],
        {
          [css['is-selected']]: listVisible,
        },
        {
          [css['ds-navigation-list-no-desktop']]: hideOnDesktop,
        },
      ])}
    >
      {showNavToggle ? (
        <h2 className={css['ds-navigation-list__header']}>
          <a
            className={css['ds-navigation-list__header-anchor']}
            onClick={toggle}
            onKeyDown={keyDown}
            role='button'
            tabIndex='0'
            aria-expanded={listVisible}
          >
            {title}
          </a>
        </h2>
      ) : (
        <h2 className={css['ds-navigation-list__header']}>{title}</h2>
      )}
      <ul
        className={classnames(css[`ds-navigation-list-items--${type}`], {
          [css['is-selected']]: listVisible,
        })}
      >
        {children}
      </ul>
    </li>
  );
};

NavigationControl.defaultProps = {
  listIsOpen: false,
  hideOnDesktop: false,
};

NavigationControl.propTypes = {
  title: PropTypes.node.isRequired,
  children: PropTypes.node.isRequired,
  type: PropTypes.node.isRequired,
  menuIsOpen: PropTypes.bool.isRequired,
  showNavToggle: PropTypes.bool.isRequired,
  listIsOpen: PropTypes.bool,
  hideOnDesktop: PropTypes.bool,
};

export default NavigationControl;
