import { Tooltip, Typography, TypographyProps } from '@mui/material';
import { useMemo } from 'react';

function shortenString(str: string | undefined, maxLength: number = 10): string {
  if (!str) return '';
  if (str.length <= maxLength) return str;
  return `${str.slice(0, maxLength - 1)}...${str.slice(-2)}`;
}

export interface ShortenLabelProps {
  children: string;
  maxLength?: number;
  sx?: TypographyProps['sx'];
  hiddenTip?: boolean;
}

function ShortenLabel({ children, maxLength = 10, sx = undefined, hiddenTip = false }: ShortenLabelProps) {
  const shortenedText = useMemo(() => shortenString(children, maxLength), [children, maxLength]);
  if (children?.length <= maxLength) {
    return <Typography sx={sx}>{children}</Typography>;
  }
  if (hiddenTip) {
    return <Typography sx={sx}>{shortenedText}</Typography>;
  }
  return (
    <Tooltip title={children} placement="top">
      <Typography sx={sx}>{shortenedText}</Typography>
    </Tooltip>
  );
}

export default ShortenLabel;
