import React, { ComponentProps, forwardRef, useEffect, useState } from 'react';
import { Menu as MuiMenu } from '@mui/material';

type Props = ComponentProps<typeof MuiMenu> & {
  anchorEl?: (EventTarget & HTMLButtonElement) | null;
};

const Menu = forwardRef<HTMLDivElement, Props>(({ anchorEl, sx, ...rest }: Props, ref) => {
  const [listWidth, setListWidth] = useState<number>(0);

  useEffect(() => {
    if (anchorEl) {
      setListWidth(anchorEl.clientWidth || 0);
    }
  }, [anchorEl]);

  return (
    <MuiMenu
      ref={ref}
      anchorEl={anchorEl}
      sx={{
        ...(listWidth > 0 && { '& .MuiPaper-root': { minWidth: listWidth } }),
        ...sx,
      }}
      {...rest}
    />
  );
});

Menu.displayName = 'Menu';

export default Menu;
