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

import Tooltip, { type TooltipProps } from '@design-system/Tooltip';
import Typography, {
  type TypographyProps,
} from '@mui/material/Typography/Typography';

type TypographyOverflowTooltipProps = {
  tooltipProps: Omit<TooltipProps, 'children'>;
  typographyProps?: TypographyProps;
  children: React.ReactNode;
};

const TOOLTIP_DELAY_DEFAULT = 400;

/** @deprecated Use TextOverflowTip instead */
const TypographyOverflowTooltip: FC<TypographyOverflowTooltipProps> = ({
  children,
  tooltipProps,
  typographyProps,
}) => {
  const [isTruncated, setIsTruncated] = useState(false);
  const textRef = useRef<HTMLElement>(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);
    };
  }, [children]);

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

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

export default TypographyOverflowTooltip;
