import React, {ReactNode, useState, useRef, useEffect} from 'react';
import ReactDOM from 'react-dom';

import './tooltip_wrapper.scss';

type TooltipWrapperProps = {
    children: ReactNode;
    tooltipContent: ReactNode;
}

const TooltipWrapper: React.FC<TooltipWrapperProps> = ({children, tooltipContent}) => {
    const [isVisible, setIsVisible] = useState(false);
    const wrapperRef = useRef<HTMLDivElement>(null);
    const tooltipRef = useRef<HTMLDivElement>(null);
    const [position, setPosition] = useState({bottom: 0, left: 0});

    const handleMouseEnter = () => setIsVisible(true);
    const handleMouseLeave = () => setIsVisible(false);

    useEffect(() => {
        if (wrapperRef.current && isVisible) {
            const wrapperRect = wrapperRef.current.getBoundingClientRect();
            setPosition({
                bottom: window.innerHeight - (wrapperRect.top + window.scrollY - 5),
                left: wrapperRect.left + window.scrollX + wrapperRect.width / 2,
            });
        }
    }, [isVisible]);

    const tooltip = (
        <div
            ref={tooltipRef}
            className='badge-tooltip'
            style={{
                position: 'absolute',
                bottom: `${position.bottom}px`,
                left: `${position.left}px`,
                transform: 'translateX(-50%)',
                visibility: isVisible ? 'visible' : 'hidden',
                opacity: isVisible ? 1 : 0,
            }}
        >
            {tooltipContent}
            <div
                className='badge-tooltip-arrow'
                style={{
                    bottom: '-4px',
                    left: '50%',
                    marginLeft: '-4px',
                }}
            />
        </div>
    );

    return (
        <div
            ref={wrapperRef}
            className='badge-tooltip-wrapper'
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
        >
            {children}
            {isVisible && ReactDOM.createPortal(tooltip as any, document.body)}
        </div>
    );
};

export default TooltipWrapper;
