import { useStyleConfig, v, vui } from '../core'
import type { MouseEvent } from '../utils'
import { cs, mergeRefs } from '../utils'
import { usePopoverContext } from './context'
import type { PopoverTriggerProps } from './popover.types'

/**
 * Displays a trigger component to toggle display of the popover content.
 * Can be rendered as any component using the 'as' prop. By default renders as a plain button.
 */
export const PopoverTrigger = vui<'button', PopoverTriggerProps>((props, ref) => {
  // @ts-expect-error TS incorrectly doesn't recognize 'as' prop
  const { as, className, onClick: onClickProp, ...rest } = props
  const { setReference, isOpen, ...popoverProps } = usePopoverContext() ?? {}
  const styles = useStyleConfig('Popover', { ...popoverProps, ...props })

  const Element = as || v.button

  const onClick = (e: MouseEvent<HTMLButtonElement>) => {
    // Avoids triggering parent's onClick, like when inside a ListItem
    e.stopPropagation()
    onClickProp?.(e)
  }

  return (
    <Element
      isActive={isOpen}
      className={cs('vui-popoverTrigger', className)}
      onClick={onClick}
      ref={mergeRefs(setReference, ref)}
      {...styles.trigger}
      {...rest}
    />
  )
})

PopoverTrigger.displayName = 'PopoverTrigger'

export default PopoverTrigger
