import React, {useEffect, useRef, useState} from "react";
import {ClickAwayListener, Grow, IconButton, MenuList, Paper, Popper} from "@material-ui/core";
import TuneIcon from "@material-ui/icons/Tune";


const OptionsDropdown = ({listId, children}) => {
  const [open, setOpen] = useState(false);
  const anchorRef = useRef(null);
  const prevOpen = useRef(open);

  const handleToggle = () => {
    setOpen((pOpen) => !pOpen);
  };

  const handleClose = (event) => {
    if (anchorRef.current && anchorRef.current.contains(event.target)) {
      return;
    }

    setOpen(false);
  };

  const handleListKeyDown = (event) => {
    if (event.key === 'Tab') {
      event.preventDefault();
      setOpen(false);
    }
  }

  useEffect(() => {
    if (prevOpen.current === true && open === false) {
      anchorRef.current.focus();
    }

    prevOpen.current = open;
  }, [open]);

  return (<div>
      <IconButton
        ref={anchorRef}
        aria-controls={open ? listId : undefined}
        aria-haspopup="true"
        onClick={handleToggle}
      >
        <TuneIcon />
      </IconButton>
      <Popper open={open} anchorEl={anchorRef.current} role={undefined} transition>
        {({TransitionProps, placement}) => (
          <Grow
            {...TransitionProps}
            style={{
              transformOrigin:
                placement ===
                'bottom' ?
                  'center top' :
                  'center bottom'
            }}
          >
            <Paper>
              <ClickAwayListener onClickAway={handleClose}>
                <MenuList
                  autoFocusItem={open}
                  id={listId}
                  onKeyDown={handleListKeyDown}
                >
                  {children}
                </MenuList>
              </ClickAwayListener>
            </Paper>
          </Grow>
        )}
      </Popper>
    </div>
  );
}

export default OptionsDropdown;