import React from "react";

import { Tooltip } from "@ax/components";

const TruncatedTooltip = ({ content, children, ...props }: any) => {
	const [isTruncated, setIsTruncated] = React.useState(false);
	const elementRef = React.useRef<HTMLElement | null>(null);

	const checkTruncation = React.useCallback(() => {
		if (elementRef.current) {
			const isTrunc = elementRef.current.scrollWidth > elementRef.current.clientWidth;
			setIsTruncated(isTrunc);
		}
	}, []);

	React.useEffect(() => {
		const element = elementRef.current;
		if (!element) return;

		checkTruncation();

		const observer = new ResizeObserver(() => {
			checkTruncation();
		});

		observer.observe(element);

		return () => {
			observer.disconnect();
		};
	}, [checkTruncation]);

	const ChildWithRef = React.cloneElement(children, {
		ref: elementRef,
	});

	if (!isTruncated) {
		return ChildWithRef;
	}

	return (
		<Tooltip content={content} {...props}>
			{ChildWithRef}
		</Tooltip>
	);
};

export default TruncatedTooltip;
