import React, { useEffect, useRef, useState } from 'react';
import { Tooltip } from './tooltip';
import { Typo, type TypoProps } from './typo';

export type EllipsisTooltipProps = TypoProps & {
  lineClamp?: number;
  children?: string;
};

export function EllipsisTooltip(
  props: EllipsisTooltipProps
): React.ReactElement {
  const { children, style, lineClamp = 2, ...rest } = props;
  const ref = useRef<HTMLSpanElement>(null);

  const [tooltipDisplay, setTooltipDisplay] = useState<'none' | 'block'>(
    'none'
  );

  useEffect(() => {
    if (ref.current) {
      const typo = ref.current;
      const mouseOver = (): void => {
        if (typo.clientHeight < typo.scrollHeight) {
          setTooltipDisplay('block');
        }
      };

      const mouseOut = (): void => {
        setTooltipDisplay('none');
      };

      ref.current.addEventListener('mouseenter', mouseOver);
      ref.current.addEventListener('mouseleave', mouseOut);
    }
  }, [children]);

  return (
    <Tooltip content={children} style={{ display: tooltipDisplay }}>
      <Typo
        {...rest}
        ref={ref}
        style={{
          width: '100%',
          textOverflow: 'ellipsis',
          overflow: 'hidden',
          WebkitLineClamp: lineClamp,

          display: '-webkit-box',
          WebkitBoxOrient: 'vertical',
          wordBreak: 'break-word',
          ...style,
        }}
      >
        {children}
      </Typo>
    </Tooltip>
  );
}
