import React, { useEffect, useRef, useState } from "react";
import './tooltip.css';

type Props = {
    message: string,
    position: 'top' | 'right' | 'bottom' | 'left',
    children: React.ReactNode,
    actions: 'hover' | 'click'
}


const Tooltip = (props:Props) => {
    const {message, position, actions, children} = props;
    const [show, setShow] = useState<boolean>(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    const tooltipShow = () => {
        setShow(!show)
    }
    useEffect(() => {
        const pageClickEvent = (e:any) => {
            if (dropdownRef.current !== null && !dropdownRef.current.contains(e.target)) {
                setShow(!show);
              }
        };
        if (show) {
            window.addEventListener('click', pageClickEvent);
        }
      return () => {    
        window.removeEventListener('click', pageClickEvent);
      }
    }, [show])
    return (
        <>
            <div className={`tooltip ${show ? 'visible' : ''} ${position ? `align-${position}` : ''}`}>
                {actions === 'hover' && 
                    <div
                        onMouseEnter={() => setShow(true)}
                        onMouseLeave={() => setShow(false)}
                    >
                        {children}
                    </div>
                }
                {actions === 'click' && 
                    <div onClick={tooltipShow}>
                        {children}
                    </div>
                }
                <span ref={dropdownRef} className="tooltip-text">{message}</span>
            </div>
        </>
    );
};

export default Tooltip;