import React, { useState } from "react"
import ReactDOM from "react-dom"
import "./Tooltip.less"

const TooltipBox = ({ children }: any) => {

  const [isTool, setTool] = useState(false)
  const [X, setX] = useState(0)
  const [Y, setY] = useState(0)

  const Tool = ({ isTool, children, X, Y }: any) => {
    if (!isTool) return null;
    return ReactDOM.createPortal(
      <div
        className="kx_tooltip"
        onMouseEnter={() => {
          setTool(isTool)
        }}
        onMouseOut={() => {
          setTool(false)
        }}
        style={{
          position: "fixed",
          bottom: Y,
          left: X,
        }}>
        {children}
      </div>,
      document.body
    );
  }

  return <>
    <Tool isTool={isTool} children={children} X={X} Y={Y} />
    <div
      style={{
        overflow: 'hidden',
        whiteSpace: 'nowrap',
        textOverflow: 'ellipsis',
      }}
    >
      <span
        onMouseEnter={(e: any) => {
          if (e.target.offsetWidth > e.target.parentNode.offsetWidth) {
            setTool(true)
            setX(e.target.getBoundingClientRect().left)
            setY(document.body.clientHeight - e.target.getBoundingClientRect().top + 10)
          }
        }}
        onMouseOut={() => {
          setTool(false)
        }}
      >
        {children}
      </span>
    </div>
  </>
}

export default TooltipBox