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

const HoverCard = HoverCardPrimitive.Root
const HoverCardTrigger = HoverCardPrimitive.Trigger

export interface HoverCardContentProps
  extends React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content> {
  /** When provided (e.g. from ThemeStyleProvider), used for portal wrapper */
  dataStyle?: string
  dataTheme?: string
}

const HoverCardContent = React.forwardRef<
  React.ElementRef<typeof HoverCardPrimitive.Content>,
  HoverCardContentProps
>(
  (
    { className, align = 'center', sideOffset = 4, children, dataStyle, dataTheme, ...props },
    ref,
  ) => {
    const fromDoc = getThemeFromDocument()
    const dataProps =
      dataStyle !== undefined
        ? { 'data-style': dataStyle, 'data-theme': dataTheme ?? fromDoc['data-theme'] ?? '' }
        : fromDoc
    return (
      <HoverCardPrimitive.Portal>
        <div style={{ display: 'contents' }} {...dataProps}>
          <HoverCardPrimitive.Content
            ref={ref}
            align={align}
            sideOffset={sideOffset}
            className={cn(
              'z-50 w-64 rounded-lg border border-border-tertiary bg-bg-container p-4 text-sm text-text shadow-md outline-none',
              className,
            )}
            {...props}
          >
            <motion.div
              {...MOTION_SCALE_IN}
            >
              {children}
            </motion.div>
          </HoverCardPrimitive.Content>
        </div>
      </HoverCardPrimitive.Portal>
    )
  },
)
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName

export { HoverCard, HoverCardTrigger, HoverCardContent }
