import React, { cloneElement } from "react"
import PropTypes from "prop-types"
import { useTooltip, TooltipPopup } from "@reach/tooltip"
import Portal from "../portal"

const centered = (triggerRect, tooltipRect) => {
  const triggerCenter = triggerRect.left + triggerRect.width / 2
  const left = triggerCenter - tooltipRect.width / 2
  const maxLeft = window.innerWidth - tooltipRect.width - 2

  return {
    left: Math.min(Math.max(2, left), maxLeft) + window.scrollX,
    top: triggerRect.bottom + 8 + window.scrollY,
  }
}

function Tooltip({ children, label }) {
  const [trigger, tooltip] = useTooltip()
  const { isVisible, triggerRect } = tooltip

  return (
    <React.Fragment>
      {cloneElement(children, trigger)}

      {isVisible && (
        <Portal>
          <div
            className="tooltip-arrow"
            style={{
              position: "absolute",
              left:
                triggerRect && triggerRect.left - 10 + triggerRect.width / 2,
              top: triggerRect && triggerRect.bottom + window.scrollY,
              width: 0,
              height: 0,
              borderLeft: "10px solid transparent",
              borderRight: "10px solid transparent",
              borderBottom: "10px solid #000000",
            }}
          />
        </Portal>
      )}
      <TooltipPopup {...tooltip} label={label} position={centered} />
    </React.Fragment>
  )
}

Tooltip.propTypes = {
  children: PropTypes.node,
  label: PropTypes.string.isRequired,
}

export default Tooltip
