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

const staticSide = {
  top: 'bottom',
  right: 'left',
  bottom: 'top',
  left: 'right'
};
export default function useTooltip(_ref) {
  let {
    container,
    style
  } = _ref;
  const theme = useTheme();
  const [title, setTitle] = useState(null);
  const [isHtmlTitle, setHtmlTitle] = useState(false);
  const arrowReference = useRef(null); // let themeClassName = style[theme.mode] || style.light;

  const 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) {
    const element = e.target;
    let titleElement = null;

    if (element.hasAttribute('data-title') || element.hasAttribute('title')) {
      titleElement = element;
    } else {
      const closedTitleElement = element.closest('[data-title]');

      if (closedTitleElement) {
        titleElement = closedTitleElement;
      }
    }

    if (titleElement) {
      const title = titleElement.getAttribute('data-title') || titleDiv.getAttribute('title');
      const isHtmlTitle = titleElement.getAttribute('data-ishtml');
      setTitle(title);
      setHtmlTitle(isHtmlTitle);
      reference(titleElement);
    } else {
      reset();
    }
  }

  function handleClick() {
    reset();
  }

  function mouseLeave() {
    reset();
  }

  const 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]);
  const arrowX = selectn('arrow.x', middlewareData);
  const arrowY = selectn('arrow.y', middlewareData);
  return {
    title,
    isHtmlTitle,
    className,
    floating,
    strategy,
    x,
    y,
    arrowReference,
    arrowX,
    arrowY,
    arrowPlacement: staticSide[placement.split('-')[0]]
  };
}