import { useStyleConfig, vui } from '../core'
import { ListItem, ListItemProps } from '../list'
import { usePopoverContext } from '../popover'
import { cs, MouseEvent, useCallbackRef } from '../utils'
import { useMenuContext } from './context'

/** Displays a list item and by default closes the menu on click. */
export const MenuItem = vui<'li', ListItemProps>((props, ref) => {
  const { className, onClick: onClickProp, ...rest } = props
  const { instance } = usePopoverContext() ?? {}
  const { closeOnSelect, ...menuProps } = useMenuContext() ?? {}
  const styles = useStyleConfig('Menu', { ...menuProps, ...props })

  const onClick = useCallbackRef((e: MouseEvent<HTMLLIElement>) => {
    onClickProp?.(e)
    closeOnSelect && instance?.hide()
  })

  return <ListItem className={cs('vui-menuItem', className)} onClick={onClick} ref={ref} {...styles.item} {...rest} />
})

MenuItem.displayName = 'MenuItem'
export default MenuItem
