import classnames from 'classnames';
import { useCallback, useEffect, useState } from 'react';
import ElectionLink from '../../ElectionLink/index.js';
import StateName from '../../StateName/index.js';
import choose from '../choose.module.scss';
import classes from './styles.module.scss';
const DesktopStates = function DesktopStates(props) {
  const {
    states,
    size,
  } = props;
  const [isOpen, setIsOpen] = useState();
  useEffect(() => {
    if (!isOpen) return undefined;
    const handler = () => setIsOpen(false);
    window.document.addEventListener('click', handler);
    return () => window.document.removeEventListener('click', handler);
  }, [isOpen]);
  const clickButton = useCallback(e => {
    e.stopPropagation();
    setIsOpen(old => !old);
  }, []);
  return (
    <div className={classes.container}>
      <button className={classnames(choose.choose, choose[size])} type='button' onClick={clickButton}>
        Choose a state
      </button>
      {isOpen && (
        <div className={classes.states}>
          {states.map(state => (
            <div key={state}>
              <ElectionLink to={`state:${state}:index`}>
                <StateName stateFips={state} />
              </ElectionLink>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
export default DesktopStates;
