import { useCallback, useRef } from 'react';

import Menu from '@design-system/Menu';

import TableMenuItem from './item';
import { type TableMenuProps } from './types';

const TableMenu = ({ anchorRef, open, options, onClose }: TableMenuProps) => {
  const submenuCloseRef = useRef<(() => void) | null>(null);

  const handleSubmenuOpen = useCallback((closeFn: () => void) => {
    // Close any previously open submenu
    if (submenuCloseRef.current !== closeFn) {
      submenuCloseRef.current?.();
    }
    // Store the new close function
    submenuCloseRef.current = closeFn;
  }, []);

  const handleSubmenuClose = useCallback((closeFn: () => void) => {
    if (submenuCloseRef.current === closeFn) {
      submenuCloseRef.current = null;
    }
  }, []);

  return (
    <Menu
      open={open}
      anchorEl={anchorRef.current}
      onClose={onClose}
      sx={{ minWidth: '200px' }}
    >
      {options.map(option => (
        <TableMenuItem
          key={option.label}
          onClose={onClose}
          onSubmenuOpen={handleSubmenuOpen}
          onSubmenuClose={handleSubmenuClose}
          {...option}
        />
      ))}
    </Menu>
  );
};

export default TableMenu;
