import {
  type BreadcrumbLink,
  type CollapsedItemsMenuProps,
} from '@design-system/Breadcrumbs/types';
import Title from '@design-system/Title';
import { Link, Paper, Popper, Stack, useTheme } from '@mui/material';

export const CollapsedItemsMenu = ({
  id,
  open,
  anchorEl,
  collapsedLinks,
  onItemClick,
}: CollapsedItemsMenuProps) => {
  const { palette, zIndex } = useTheme();

  const handleItemClick =
    (link: BreadcrumbLink): React.MouseEventHandler =>
    event => {
      event.stopPropagation();
      link.onClick?.(event as React.MouseEvent<HTMLAnchorElement>);
      onItemClick();
    };

  return (
    <Popper
      open={open}
      anchorEl={anchorEl}
      sx={{ zIndex: zIndex.tooltip }}
    >
      <Stack
        component={Paper}
        elevation={2}
        id={id}
        role="menu"
        sx={{ mt: 1, maxWidth: 200, overflow: 'hidden' }}
      >
        {collapsedLinks.map(link => (
          <Link
            key={`${link.title}-${link.href}`}
            role="menuitem"
            href={link.href}
            onClick={handleItemClick(link)}
            {...(link.component && { component: link.component })}
            sx={{
              cursor: 'pointer',
              p: 1,
              textDecoration: 'none',
              color: 'inherit',
              ':hover': {
                backgroundColor: palette.new.action.background.neutral.hover,
              },
            }}
          >
            <Title
              variant="S"
              title={link.title}
              withEllipsis
              overflow="tooltip"
            />
          </Link>
        ))}
      </Stack>
    </Popper>
  );
};
