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

const Tooltip = ({ children, text, position = 'top' }) => {
    const [visible, setVisible] = useState(false);
    const [coords, setCoords] = useState({ top: 0, left: 0 });
    const triggerRef = useRef(null);
    const timeoutRef = useRef(null);

    const showTooltip = () => {
        timeoutRef.current = setTimeout(() => {
            if (triggerRef.current) {
                const rect = triggerRef.current.getBoundingClientRect();
                let top, left;

                switch (position) {
                    case 'bottom':
                        top = rect.bottom + 8;
                        left = rect.left + rect.width / 2;
                        break;
                    case 'left':
                        top = rect.top + rect.height / 2;
                        left = rect.left - 8;
                        break;
                    case 'right':
                        top = rect.top + rect.height / 2;
                        left = rect.right + 8;
                        break;
                    default: // top
                        top = rect.top - 8;
                        left = rect.left + rect.width / 2;
                        break;
                }
                setCoords({ top, left });
                setVisible(true);
            }
        }, 200);
    };

    const hideTooltip = () => {
        if (timeoutRef.current) clearTimeout(timeoutRef.current);
        setVisible(false);
    };

    useEffect(() => {
        return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
    }, []);

    const getTransformStyle = () => {
        switch (position) {
            case 'bottom': return 'translate(-50%, 0)';
            case 'left': return 'translate(-100%, -50%)';
            case 'right': return 'translate(0, -50%)';
            default: return 'translate(-50%, -100%)';
        }
    };

    const getArrowClass = () => `tooltip-arrow tooltip-arrow-${position}`;

    return (
        <>
            <div
                ref={triggerRef}
                onMouseEnter={showTooltip}
                onMouseLeave={hideTooltip}
                style={{ display: 'inline-flex' }}
            >
                {children}
            </div>
            {visible && ReactDOM.createPortal(
                <div
                    className="tooltip"
                    style={{
                        position: 'fixed',
                        top: coords.top,
                        left: coords.left,
                        transform: getTransformStyle(),
                        zIndex: 10001,
                    }}
                >
                    {text}
                    <div className={getArrowClass()} />
                </div>,
                document.body
            )}
        </>
    );
};

export default Tooltip;
