import styles from './index.less';
import { useState, useRef, useEffect, } from 'react';

export default function ToolTips({children, className, style, tips, topLeft }) {
  const [visible, toggleVisible] = useState(false);
  const timer = useRef(null);
  function showTips(e) {
    e.stopPropagation();
    if (timer.current !== null) {
      clearTimeout(timer.current);
    }
    toggleVisible(true);
    timer.current = setTimeout(() => {
      toggleVisible(false);
      timer.current = null;
    }, 1000)
  }
  const tipsContainer = useRef();
  const [top, setTop] = useState('calc(-22px + -0.16rem)');
  useEffect(() => {
    if (tipsContainer && tipsContainer.current) {
      const { height } = tipsContainer.current.getBoundingClientRect();
      setTop(`calc(-${height}px + -0.16rem)`);
    }
  }, [visible]);
  const tipsContainerClassNames = [styles.tipsContainer];
  const triangleClassNames = [styles.tri];
  if (topLeft) {
    tipsContainerClassNames.push(styles.topLeft);
    triangleClassNames.push(styles.topLeft);
  }
  return (
    <div className={styles.container + ' ' +  (className || '')} style={style} onClick={showTips}>
      {children}
      {
        visible && (
          <div className={tipsContainerClassNames.join(' ')} style={{top: top}} ref={tipsContainer}>
            {tips}
            <div className={triangleClassNames.join(' ')}></div>
          </div>
        )
      }
    </div>
  )
}
