import { useState, useEffect, useRef } from 'react';
import { useFloating, shift, flip, arrow, offset } from '@floating-ui/react-dom';
import compileClassNames from '../../../libraries/compileClassNames'
import { useTheme } from "../../uclprovider/UCLProvider";
import selectn from 'selectn'
import debounce from '../../../utils/debounce'

const staticSide = {
    top: 'bottom',
    right: 'left',
    bottom: 'top',
    left: 'right'
};

export default function useTooltip({ container, style }) {
    const theme = useTheme();
    let [title, setTitle] = useState(null);
    let [isHtmlTitle, setHtmlTitle] = useState(false)
    let arrowReference = useRef(null);
    let themeClassName = style[theme.mode] || style.light;
    let className = compileClassNames({
        [style.tooltipContainer]: true,
        [style.show]: title != null,
        [themeClassName]: true
    })
    const { x, y, reference, floating, strategy, middlewareData, placement } =
        useFloating({
            placement: 'bottom',
            middleware: [offset(6), flip(), shift(), arrow({ element: arrowReference })]
        });
    function reset() {
        if (title) {
            setTitle(null);
            setHtmlTitle(false);
        }
    }
    function mouseHover(e) {
        let element = e.target;
        let titleElement = null;
        if (element.hasAttribute('data-title') || element.hasAttribute('title')) {
            titleElement = element;
        } else {
            let closedTitleElement = element.closest('[data-title]');
            if (closedTitleElement) {
                titleElement = closedTitleElement;
            }
        }
        if (titleElement) {
            let title =
                titleElement.getAttribute('data-title') || titleDiv.getAttribute('title');
            let isHtmlTitle = titleElement.getAttribute('data-ishtml');
            setTitle(title);
            setHtmlTitle(isHtmlTitle)
            reference(titleElement);
        }
        else {
            reset();
        }
    }
    function handleClick() {
        reset();
    }
    function mouseLeave() {
        reset();
    }

    let mouseHoverDebounced = debounce(mouseHover, 300);
    useEffect(() => {
        container.addEventListener("mouseover", mouseHoverDebounced)
        container.addEventListener("mouseleave", mouseLeave);
        container.addEventListener("click", handleClick)
        return () => {
            container.removeEventListener("mouseover", mouseHoverDebounced);
            container.removeEventListener("mouseleave", mouseLeave);
            container.removeEventListener("click", handleClick)
        }
    }, [title, container])
    let arrowX = selectn("arrow.x", middlewareData);
    let arrowY = selectn("arrow.y", middlewareData);
    return {
        title, isHtmlTitle, className, floating,
        strategy, x, y, arrowReference, arrowX, arrowY,
        arrowPlacement: staticSide[placement.split('-')[0]]
    }
}