import { type FC, useLayoutEffect, useRef, useState } from 'react';

import Typography, { type TypographyProps } from '@material-hu/mui/Typography';

import HuTooltip from '@material-hu/components/design-system/Tooltip';
import { type TooltipProps as HuTooltipProps } from '@material-hu/components/design-system/Tooltip/types';

type Props = {
  text: string;
  tooltipProps?: HuTooltipProps;
  typographyProps?: TypographyProps;
};

const TypographyOverflowTooltip: FC<Props> = ({
  text,
  tooltipProps,
  typographyProps,
}) => {
  const [isTruncated, setIsTruncated] = useState(false);
  const textRef = useRef<HTMLSpanElement>(null);

  useLayoutEffect(() => {
    const checkTruncation = () => {
      if (textRef.current) {
        const element = textRef.current;
        setIsTruncated(element.scrollWidth > element.clientWidth);
      }
    };

    checkTruncation();
    window.addEventListener('resize', checkTruncation);

    return () => {
      window.removeEventListener('resize', checkTruncation);
    };
  }, [text]);

  const { sx, ...rest } = typographyProps ?? {};

  return (
    <HuTooltip
      description={text}
      disableTooltip={!isTruncated}
      direction="top"
      delay={400}
      {...tooltipProps}
    >
      <Typography
        ref={textRef}
        sx={{
          display: 'block',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
          width: 1,
          ...sx,
        }}
        {...rest}
      >
        {text}
      </Typography>
    </HuTooltip>
  );
};

export default TypographyOverflowTooltip;
