import { useEffect, useRef, useState } from 'react';

import Typography from '@material-hu/mui/Typography';

import Tooltip from '@material-hu/components/design-system/Tooltip';

type TooltipTextProps = {
  text: string;
};

const TooltipText = ({ text }: TooltipTextProps) => {
  const textRef = useRef<HTMLSpanElement | null>(null);
  const [isTruncated, setIsTruncated] = useState(false);

  useEffect(() => {
    if (!textRef.current) return;
    const { scrollWidth, clientWidth } = textRef.current;
    setIsTruncated(scrollWidth > clientWidth);
  }, [text]);

  return (
    <Tooltip
      description={isTruncated ? text : ''}
      direction="bottom"
      disableTooltip={!isTruncated}
    >
      <Typography
        ref={textRef}
        variant="globalXS"
        sx={{
          color: theme => theme.palette.textColors?.neutralTextLighter,
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
          maxWidth: '100%',
          display: 'block',
        }}
      >
        {text}
      </Typography>
    </Tooltip>
  );
};

export default TooltipText;
