import { Tooltip, Typography } from '@mui/material';
import type { TooltipProps } from '@mui/material';
import { tooltipClasses } from '@mui/material/Tooltip';
import { styled } from '@mui/system';
import { truncateText } from '../libs/util';

const CustomTooltip = styled(({ className, ...props }: TooltipProps) => (
  <Tooltip {...props} classes={{ popper: className }} />
))({
  [`& .${tooltipClasses.tooltip}`]: {
    fontSize: 11,
    maxHeight: 120,
    maxWidth: 500,
    overflowY: 'auto',
  },
});

interface TruncatedTextProps {
  text?: string;
  maxLength?: number;
  useWidth?: boolean;
}

export default function TruncatedText({ text = '', maxLength = 100, useWidth = false }: TruncatedTextProps) {
  if (!text) {
    return null;
  }
  const truncatedText = truncateText(text, maxLength, useWidth);
  if (!truncatedText.endsWith('...')) {
    return <Typography>{truncatedText}</Typography>;
  }
  return (
    <CustomTooltip title={text} placement="bottom" enterTouchDelay={0}>
      <Typography>{truncatedText}</Typography>
    </CustomTooltip>
  );
}
