import * as React from 'react'
import { motion } from 'framer-motion'
import * as PopoverPrimitive from '@radix-ui/react-popover'
import { cn } from '@/lib/utils'
import { MOTION_SCALE_IN } from '@/lib/motion'
import { getThemeFromDocument } from './theme-from-document'

const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverAnchor = PopoverPrimitive.Anchor

export interface PopoverContentProps
  extends React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content> {
  /** When provided (e.g. from ThemeStyleProvider), used for portal wrapper */
  dataStyle?: string
  dataTheme?: string
  /** Popover internal padding; keep default to avoid breaking existing usages */
  contentPadding?: 'default' | 'compact' | 'none'
}

const PopoverContent = React.forwardRef<
  React.ElementRef<typeof PopoverPrimitive.Content>,
  PopoverContentProps
>(
  (
    {
      className,
      align = 'center',
      sideOffset = 4,
      contentPadding = 'default',
      children,
      dataStyle,
      dataTheme,
      ...props
    },
    ref,
  ) => {
    const fromDoc = getThemeFromDocument()
    const dataProps =
      dataStyle !== undefined
        ? { 'data-style': dataStyle, 'data-theme': dataTheme ?? fromDoc['data-theme'] ?? '' }
        : fromDoc
    return (
      <PopoverPrimitive.Portal>
        <div style={{ display: 'contents' }} {...dataProps}>
          <PopoverPrimitive.Content
            ref={ref}
            data-slot="popover-content"
            align={align}
            sideOffset={sideOffset}
            className={cn(
              'z-50 w-72 rounded-lg border border-border-tertiary bg-bg-container text-sm text-text shadow-md outline-none',
              contentPadding === 'none'
                ? 'p-0'
                : contentPadding === 'compact'
                  ? 'p-1'
                  : 'p-4',
              className,
            )}
            {...props}
          >
            <motion.div
              {...MOTION_SCALE_IN}
            >
              {children}
            </motion.div>
          </PopoverPrimitive.Content>
        </div>
      </PopoverPrimitive.Portal>
    )
  },
)
PopoverContent.displayName = PopoverPrimitive.Content.displayName

export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent }
