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

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

const EllipsisTooltip: React.FC<{
  title: string;
  children: React.ReactElement;
  delay?: number;
}> = ({ title, children, delay = undefined }) => {
  const textRef = useRef<HTMLElement>(null);
  const [isOverflowed, setIsOverflowed] = useState(false);

  const handleMouseEnter = () => {
    const el = textRef.current;
    if (el) {
      setIsOverflowed(el.scrollWidth > el.clientWidth);
    }
  };

  return (
    <HuTooltip
      title={title}
      disableTooltip={!isOverflowed}
      delay={delay}
    >
      {React.cloneElement(children, {
        ref: textRef,
        onMouseEnter: handleMouseEnter,
      })}
    </HuTooltip>
  );
};

export default EllipsisTooltip;
