import { useState } from 'react';

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

import { CollapsedItemsPopper } from './CollapsedItemsPopper';

type CustomCollapsedIconProps = {
  collapsedLinks: BreadcrumbLink[];
  darkBackground?: boolean;
};

export const CustomCollapsedIcon = ({
  collapsedLinks,
  darkBackground,
}: CustomCollapsedIconProps) => {
  const [popperAnchorEl, setPopperAnchorEl] = useState<null | HTMLElement>(
    null,
  );
  const theme = useTheme();

  const open = Boolean(popperAnchorEl);
  const id = open ? 'simple-popper' : undefined;

  const onClickEllipsis = (
    event: React.MouseEvent<HTMLElement, MouseEvent>,
  ) => {
    event.stopPropagation();
    setPopperAnchorEl(popperAnchorEl ? null : event.currentTarget);
  };
  const onClickAway = () => {
    setPopperAnchorEl(null);
  };

  return (
    <Link
      sx={{
        textDecoration: 'underline',
        // make underline white
        color: darkBackground
          ? theme.palette.new.text.neutral.inverted
          : 'inherit',
        cursor: 'pointer',
      }}
      aria-describedby={id}
    >
      <ClickAwayListener onClickAway={onClickAway}>
        <Box sx={{ position: 'relative' }}>
          <Box onClick={onClickEllipsis}>...</Box>
          {popperAnchorEl ? (
            <CollapsedItemsPopper
              id={id}
              open={open}
              anchorEl={popperAnchorEl}
              collapsedLinks={collapsedLinks}
            />
          ) : null}
        </Box>
      </ClickAwayListener>
    </Link>
  );
};
