import React from 'react'

import Box from '../box'
import { useStyleConfig, v, vui } from '../core'
import { cs, mergeRefs } from '../utils'
import { usePopoverContext } from './context'
import { PopoverContentProps } from './popover.types'

/** Displays provided content in an overlaying wrapper. */
export const PopoverContent = vui<'div', PopoverContentProps>((props, ref) => {
  const { children, className, ...rest } = props
  const popoverProps = usePopoverContext() ?? {}
  const { isLazy, isOpen, setPopper } = popoverProps
  const styles = useStyleConfig('Popover', { ...popoverProps, ...props })

  const shouldRenderChildren = isLazy ? isOpen : true

  return (
    // Wrapping div prevents an error thrown when conditionally unmounting this component
    <v.div className="vui-popoverContainer" ring={0}>
      <Box
        bg="white"
        borderRadius="md"
        boxShadow="2"
        className={cs('vui-popoverContent', className)}
        overflowY="auto"
        ref={mergeRefs(setPopper, ref)}
        ring={0}
        {...styles.content}
        {...rest}
      >
        {shouldRenderChildren ? children : null}
      </Box>
    </v.div>
  )
})

PopoverContent.displayName = 'PopoverContent'

export default PopoverContent
