/* eslint-disable import/no-extraneous-dependencies */
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import styles from './tooltip.module.scss';

const Tooltip = ({ content, delay = 0, children, direction, minWidth = 10 }) => {
  let timeout;
  const [active, setActive] = useState(false);

  const getPositionClass = (target) => {
    const tooltipChildren = target?.parentNode?.children || [];

    // eslint-disable-next-line no-restricted-syntax
    for (const element of tooltipChildren) {
      if (element?.tagName === 'DIV' && [...element?.classList].includes(styles.wrapper)) {
        const { left } = element.getBoundingClientRect();

        const tooltipWidth = left + minWidth * 6;

        if (tooltipWidth > document.body.clientWidth || tooltipWidth < 0) {
          element.classList.add(styles.staticLeft);
        }
        if (left - minWidth * 6 < 0) {
          element.classList.add(styles.staticRight);
        }
        break;
      }
    }
  };

  const showTip = () => {
    timeout = setTimeout(() => {
      setActive(!active);
    }, delay || 400);
  };

  const hideTip = () => {
    clearInterval(timeout);
    setActive(false);
  };

  return (
    // eslint-disable-next-line jsx-a11y/interactive-supports-focus, jsx-a11y/click-events-have-key-events
    <div
      className={styles?.wrapper || ''}
      onMouseEnter={showTip}
      onMouseLeave={hideTip}
      onClick={(e) => {
        getPositionClass(e.target, styles);
        showTip();
      }}
      role="button"
    >
      {children}
      {active && (
        <div
          style={{ minWidth: `${minWidth}rem` }}
          className={`${styles?.tooltip || ''} ${
            styles[direction] ? styles[direction] || '' : styles.top || ''
          }`}
        >
          <span>{content}</span>
        </div>
      )}
    </div>
  );
};

export default Tooltip;

Tooltip.propTypes = {
  delay: PropTypes.number,
  direction: PropTypes.string,
  content: PropTypes.string,
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),
  minWidth: PropTypes.number,
};
