import { MouseEvent, useCallback, useState } from 'react';

function usePopoverState() {
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const open = Boolean(anchorEl);
  const handleClick = useCallback(
    (e: MouseEvent<HTMLElement> | undefined) => setAnchorEl(e?.currentTarget ?? null),
    [setAnchorEl]
  );
  const handleClose = useCallback(() => setAnchorEl(null), [setAnchorEl]);
  const handleToggle = useCallback(
    (e: MouseEvent<HTMLElement> | undefined) => {
      if (!open) {
        handleClick(e);
      } else {
        handleClose();
      }
    },
    [open, handleClick, handleClose]
  );

  return {
    anchorEl: anchorEl,
    open: open,
    handleClick: handleClick,
    handleClose: handleClose,
    handleToggle: handleToggle
  };
}

export { usePopoverState };
