// @flow
import React, { useState, useCallback } from 'react';
import { Popper } from '../popper';
import { TooltipView } from './tooltip-view';
import type { TooltipProps } from './tooltip.proptypes';
import { Box } from '../../../primitives';

const useTooltipState = () => {
  const [isVisible, setIsVisible] = useState();

  const handleShowTooltip = useCallback(() => {
    setIsVisible(true);
  }, [setIsVisible]);
  const handleHideTooltip = useCallback(() => {
    setIsVisible(false);
  }, [setIsVisible]);

  return {
    isVisible,
    handleShowTooltip,
    handleHideTooltip,
  };
};

export const Tooltip = ({
  reference,
  placement,
  children,
  spacing,
  align,
  stacked,
  justify,
  wrap,
  ...props
}: TooltipProps) => {
  const { isVisible, handleShowTooltip, handleHideTooltip } = useTooltipState();

  return (
    <Popper
      placement={placement}
      isVisible={isVisible}
      reference={({ ref, referenceProps }) =>
        reference({
          ref,
          referenceProps: {
            ...referenceProps,
            onMouseEnter: handleShowTooltip,
            onMouseLeave: handleHideTooltip,
            onFocus: handleShowTooltip,
            onBlur: handleHideTooltip,
          },
        })
      }
      {...props}
    >
      {({ ref, style, placement: popperPlacement, arrowProps, popperId }) => (
        <TooltipView
          ref={ref}
          style={style}
          placement={popperPlacement}
          arrowProps={arrowProps}
          popperId={popperId}
        >
          <Box {...{ spacing, align, stacked, justify, wrap }}>{children}</Box>
        </TooltipView>
      )}
    </Popper>
  );
};

Tooltip.displayName = 'Tooltip';
