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

import { useTestIdAttribute } from '../../hooks/useTestIdAttribute';
import { Tooltip } from '../Tooltip/Tooltip';

import { StyledTextAutoTooltip } from './styled';

type TextAutoTooltipProps = PropsWithChildren & {
  testId?: string;
};

export const TextAutoTooltip = ({ children, testId }: TextAutoTooltipProps) => {
  const testIdAttribute = useTestIdAttribute();
  const [enabledTooltip, setToolTipEnabled] = useState(false);
  const innerRef = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    const resizeObserver = new ResizeObserver(() => {
      /* istanbul ignore next */
      setToolTipEnabled((innerRef.current?.offsetWidth ?? 0) < (innerRef.current?.scrollWidth ?? 0));
    });

    if (innerRef.current?.parentElement) {
      resizeObserver.observe(innerRef.current.parentElement);
    }
    return () => {
      resizeObserver.disconnect();
    };
  }, []);

  if (enabledTooltip) {
    return (
      <Tooltip text={children}>
        <StyledTextAutoTooltip ref={innerRef} {...{ [testIdAttribute]: testId }}>
          {children}
        </StyledTextAutoTooltip>
      </Tooltip>
    );
  }

  return (
    <StyledTextAutoTooltip ref={innerRef} {...{ [testIdAttribute]: testId }}>
      {children}
    </StyledTextAutoTooltip>
  );
};
