import * as PopoverPrimitive from '@radix-ui/react-popover'
import type * as React from 'react'
import { cn } from '../../utils'
import { typographyVariants } from '../Typography'

const Popover = PopoverPrimitive.Root
Popover.displayName = 'Popover'

const PopoverTrigger = PopoverPrimitive.Trigger

export const popoverContentClassName = cn(
  'z-50 max-w-[254px] origin-[--radix-tooltip-content-transform-origin] overflow-hidden rounded-lg bg-popover px-4 py-2',
  typographyVariants({
    variant: 'body-xs',
    color: 'popover-muted',
  }),
)

type PopoverContentProps = React.ComponentPropsWithoutRef<
  typeof PopoverPrimitive.Content
> & {
  ref?: React.Ref<React.ElementRef<typeof PopoverPrimitive.Content>>
}

const PopoverContent = ({
  className,
  sideOffset = 4,
  ref,
  ...props
}: PopoverContentProps) => (
  <PopoverPrimitive.Portal>
    <PopoverPrimitive.Content
      ref={ref}
      sideOffset={sideOffset}
      className={cn('pointer-events-auto', popoverContentClassName, className)}
      {...props}
    />
  </PopoverPrimitive.Portal>
)

type PopoverArrowProps = React.ComponentPropsWithoutRef<
  typeof PopoverPrimitive.Arrow
> & {
  ref?: React.Ref<React.ElementRef<typeof PopoverPrimitive.Arrow>>
}

const PopoverArrow = ({ className, ref, ...props }: PopoverArrowProps) => (
  <PopoverPrimitive.Arrow
    ref={ref}
    className={cn('fill-popover', className)}
    {...props}
  />
)
PopoverArrow.displayName = PopoverPrimitive.Arrow.displayName

PopoverContent.displayName = PopoverPrimitive.Content.displayName

function PopoverAnchor({
  ...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
  return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}

export { Popover, PopoverTrigger, PopoverContent, PopoverArrow, PopoverAnchor }
