// @flow
import React, { useMemo } from 'react';
import { v4 } from 'uuid';
import { Manager, Reference, Popper as ReactPopper } from 'react-popper';
import type { PopperProps } from './popper.proptypes';

export const Popper = ({
  reference,
  placement,
  children,
  isVisible,
}: PopperProps) => {
  const popperId = useMemo(() => `popper-${v4()}`, []);

  return (
    <Manager>
      <Reference>
        {({ ref }) =>
          reference({
            ref,
            referenceProps: {
              'aria-describedby': popperId,
            },
          })
        }
      </Reference>
      <ReactPopper placement={placement}>
        {({ ref, style, placement: popperPlacement, arrowProps }) =>
          isVisible ? (
            children({
              ref,
              style,
              placement: popperPlacement,
              arrowProps,
              popperId,
            })
          ) : (
            <></>
          )
        }
      </ReactPopper>
    </Manager>
  );
};

Popper.displayName = 'Popper';
