import { useState } from 'react';

import { type CollapsedIconProps } from '@design-system/Breadcrumbs/types';
import { ClickAwayListener, Link, Stack, useTheme } from '@mui/material';

import { CollapsedItemsMenu } from './CollapsedItemsMenu';

export const CollapsedIcon = ({
  collapsedLinks,
  darkBackground,
}: CollapsedIconProps) => {
  const theme = useTheme();
  const [menuAnchorEl, setMenuAnchorEl] = useState<null | HTMLElement>(null);
  const open = Boolean(menuAnchorEl);

  const handleClickEllipsis = (event: React.MouseEvent<HTMLSpanElement>) => {
    event.stopPropagation();
    setMenuAnchorEl(menuAnchorEl ? null : event.currentTarget);
  };

  const handleClickAway = () => setMenuAnchorEl(null);

  return (
    <Link
      component="span"
      sx={{
        textDecoration: 'underline',
        color: darkBackground
          ? theme.palette.new.text.neutral.inverted
          : 'inherit',
        cursor: 'pointer',
      }}
    >
      <ClickAwayListener onClickAway={handleClickAway}>
        <Stack
          component="span"
          sx={{ position: 'relative' }}
        >
          <Stack
            component="span"
            role="button"
            onClick={handleClickEllipsis}
            sx={{
              padding: 0,
              cursor: 'inherit',
              font: 'inherit',
              color: 'inherit',
            }}
          >
            ...
          </Stack>
          {menuAnchorEl && (
            <CollapsedItemsMenu
              id="breadcrumb-collapsed-menu"
              open={open}
              anchorEl={menuAnchorEl}
              collapsedLinks={collapsedLinks}
              onItemClick={handleClickAway}
            />
          )}
        </Stack>
      </ClickAwayListener>
    </Link>
  );
};
