import React, { useState } from 'react'
import styled from 'styled-components'

export type TooltipProps = {
  /**
   * text to display on hover
   */
  content: string;
  /**
   * tooltip direction
   */
  direction?: string;
  children: React.ReactNode
  /**
   * additional css that you might want to use to style the tooltip
   */
  css?: string;
};

export const Tooltip = ({ children,content,css,direction }: TooltipProps):JSX.Element  => {
  const [active, setActive] = useState(false)

  const showTip = () => {
    setActive(true)
  }

  const hideTip = () => {
    setActive(false)
  }

  return (
    <Wrapper
      onMouseEnter={showTip}
      onMouseLeave={hideTip}
      css={css}>
      {children}
      {active && (
        <ToolTip className={direction || 'top'}>
          {content}
        </ToolTip>
      )}
    </Wrapper>
  )
}

const Wrapper = styled.div<{css?: string}>`
  display: inline-block;
  position: relative;

  ${(p) => p.css}
`

const ToolTip = styled.div`
  position: absolute;
  border-radius: 4px;
  left: 50%;
  transform: translateX(-50%);
  padding: 6px;
  color: black;
  box-shadow: 1px 1px 20px #aaa;
  background: #fff;
  font-size: 14px;
  font-family: sans-serif;
  line-height: 1;
  z-index: 100;
  white-space: nowrap;
  padding: 10px;
  font-size: 0.9rem;

  ::before {
    content: " ";
    left: 50%;
    border: solid transparent;
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-width: 6px;
    margin-left: calc(6px * -1);
  }

  &.top {
    top: calc(50px * -1);
  }

  &.top::before {
    top: 100%;
    border-top-color:#fff;
  }

  &.right {
    left: calc(100% + 20px);
    top: 50%;
    transform: translateX(0) translateY(-50%);
  }

  &.right::before {
    left: calc(6px * -1);
    top: 50%;
    transform: translateX(0) translateY(-50%);
    border-right-color: white;
  }

  &.bottom {
    bottom: calc(50px * -1);
  }

  &.bottom::before {
    bottom: 100%;
    border-bottom-color: white;
  }

  &.left {
    left: auto;
    right: calc(100% + 20px);
    top: 50%;
    transform: translateX(0) translateY(-50%);
  }

  &.left::before {
    left: auto;
    right: calc(6px * -2);
    top: 50%;
    transform: translateX(0) translateY(-50%);
    border-left-color:white;
  }
`