import Tooltip from '@design-system/Tooltip';
import useOverflowed from '@hooks/useOverflowed';
import { Link as MuiLink, Typography, useTheme } from '@mui/material';

import { type BreadcrumbsItemTextProps } from '../types';

const ellipsisSx = {
  display: 'block',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  whiteSpace: 'nowrap',
  minWidth: 0,
  maxWidth: '100%',
} as const;

export const BreadcrumbsItemText = ({
  link,
  isLink,
  darkBackground,
}: BreadcrumbsItemTextProps) => {
  const theme = useTheme();
  const { ref, overflowed } = useOverflowed();

  const content = isLink ? (
    <MuiLink
      ref={ref}
      href={link.href}
      onClick={link.onClick}
      component={link.component ?? 'a'}
      sx={ellipsisSx}
    >
      {link.title}
    </MuiLink>
  ) : (
    <Typography
      ref={ref}
      variant="globalS"
      sx={{
        color: darkBackground
          ? theme.palette.new.text.neutral.inverted
          : theme.palette.new.text.neutral.default,
        ...ellipsisSx,
      }}
    >
      {link.title}
    </Typography>
  );

  return (
    <Tooltip
      disableTooltip={!overflowed}
      description={link.title}
    >
      {content}
    </Tooltip>
  );
};
