import React from 'react'

import { filterUndefined, runIfFn } from '../utils'
import { PopoverProvider } from './context'
import { PopoverProps } from './popover.types'
import PopoverContent from './popoverContent'
import PopoverTrigger from './popoverTrigger'
import usePopover from './usePopover'

/**
 * Uses 'usePopover' hook to expose relevant data to its children parts.
 * By default, renders provided content only when popover is opened (lazy).
 */
export default function Popover(props: PopoverProps) {
  const { children, isLazy = true, options, ...rest } = props
  const popoverProps = usePopover({ options, ...rest })
  const { close, isOpen, open } = popoverProps
  const context = filterUndefined({ isLazy, ...popoverProps })

  return <PopoverProvider value={context}>{runIfFn(children, { close, isOpen, open })}</PopoverProvider>
}

Popover.Content = PopoverContent
Popover.Trigger = PopoverTrigger
Popover.displayName = 'Popover'
