'use client'

import clsx from 'clsx'
import { type ComponentProps, type ReactNode } from 'react'

import { Popover as RadixPopover } from 'radix-ui'

import { contentStyles } from './Popover.styles'

type PopoverProps = ComponentProps<typeof RadixPopover.Root> &
	ComponentProps<typeof RadixPopover.Content> & {
		trigger: ReactNode
		arrow?: boolean
	}

function Popover({
	trigger,
	arrow = true,
	sideOffset,
	align,
	alignOffset,
	children,
	className,
	...props
}: PopoverProps) {
	return (
		<RadixPopover.Root {...props}>
			<RadixPopover.Trigger asChild>{trigger}</RadixPopover.Trigger>
			<RadixPopover.Portal>
				<RadixPopover.Content
					align={align}
					sideOffset={sideOffset}
					alignOffset={alignOffset}
					onOpenAutoFocus={e => e.preventDefault()}
					onCloseAutoFocus={e => e.preventDefault()}
					className={clsx(contentStyles, className)}
				>
					{children}
					{arrow && <RadixPopover.Arrow />}
				</RadixPopover.Content>
			</RadixPopover.Portal>
		</RadixPopover.Root>
	)
}

export { Popover }
