import React, { useState, ReactElement } from "react";
import cn from "classnames";
import { Manager, Reference, Popper, PopperProps } from "react-popper";

interface ITooltipProps {
  reference: ReactElement;
  tooltip?: ReactElement | ReactElement[] | string;
  placement: PopperProps["placement"];
  ["data-testid"]?: string;
}

const Tooltip: React.FC<ITooltipProps> = props => {
  const { reference, tooltip, placement, children } = props;
  const dataTestId = props["data-testid"] || "honey-ui-tooltip";

  const [isShow, setIsShow] = useState(false);

  return (
    <Manager>
      <Reference>
        {({ ref }) =>
          React.cloneElement(reference, {
            ref,
            onMouseEnter: () => setIsShow(true),
            onMouseLeave: () => setIsShow(false)
          })
        }
      </Reference>
      <Popper placement={placement}>
        {({ ref, style, arrowProps, placement: actualPlacement }) => (
          <div
            ref={ref}
            style={style}
            data-placement={actualPlacement}
            className={cn("tooltip", `bs-tooltip-${actualPlacement}`, {
              fade: !isShow,
              show: isShow,
              visible: isShow,
              invisible: !isShow
            })}
            role="tooltip"
            data-testid={dataTestId}
          >
            <div ref={arrowProps.ref} style={arrowProps.style} className="arrow" />
            {tooltip ? <div className="tooltip-inner">{tooltip}</div> : children}
          </div>
        )}
      </Popper>
    </Manager>
  );
};

Tooltip.displayName = "Tooltip";

export default Tooltip;
