import * as React from 'react'
import { motion } from 'framer-motion'
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/lib/utils'
import { MOTION_FADE, MOTION_SLIDE_UP } from '@/lib/motion'
import { getThemeFromDocument } from './theme-from-document'

const AlertDialog = AlertDialogPrimitive.Root
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
const AlertDialogPortal = AlertDialogPrimitive.Portal

const AlertDialogOverlay = React.forwardRef<
  React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
  <AlertDialogPrimitive.Overlay ref={ref} asChild {...props}>
    <motion.div
      className={cn('fixed inset-0 z-50 bg-bg-mask/60', className)}
      {...MOTION_FADE}
    />
  </AlertDialogPrimitive.Overlay>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName

const contentVariants = cva(
  'font-sans fixed left-1/2 top-1/2 z-50 w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-bg-base text-text shadow-lg p-6',
  {
    variants: {
      size: { default: 'max-w-lg', sm: 'max-w-sm' },
    },
    defaultVariants: { size: 'default' },
  }
)

export interface AlertDialogContentProps
  extends React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>,
    VariantProps<typeof contentVariants> {
  size?: 'default' | 'sm'
  /** When provided (e.g. from ThemeStyleProvider), used for portal wrapper */
  dataStyle?: string
  dataTheme?: string
}

const AlertDialogContent = React.forwardRef<
  React.ElementRef<typeof AlertDialogPrimitive.Content>,
  AlertDialogContentProps
>(({ className, children, size = 'default', dataStyle, dataTheme, ...props }, ref) => {
  const fromDoc = getThemeFromDocument()
  const dataProps =
    dataStyle !== undefined
      ? { 'data-style': dataStyle, 'data-theme': dataTheme ?? fromDoc['data-theme'] ?? '' }
      : fromDoc
  return (
    <AlertDialogPortal>
      <div style={{ display: 'contents' }} {...dataProps}>
        <AlertDialogOverlay />
        <AlertDialogPrimitive.Content ref={ref} asChild {...props}>
          <motion.div
            className={cn(contentVariants({ size }), className)}
            {...MOTION_SLIDE_UP}
          >
            {children}
          </motion.div>
        </AlertDialogPrimitive.Content>
      </div>
    </AlertDialogPortal>
  )
})
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName

const AlertDialogHeader = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
  <div ref={ref} className={cn('flex flex-col gap-2', className)} {...props} />
))
AlertDialogHeader.displayName = 'AlertDialogHeader'

const AlertDialogFooter = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn('mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
    {...props}
  />
))
AlertDialogFooter.displayName = 'AlertDialogFooter'

const AlertDialogTitle = React.forwardRef<
  React.ElementRef<typeof AlertDialogPrimitive.Title>,
  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
  <AlertDialogPrimitive.Title
    ref={ref}
    className={cn('font-sans text-base font-medium leading-6 text-text', className)}
    {...props}
  />
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName

const AlertDialogDescription = React.forwardRef<
  React.ElementRef<typeof AlertDialogPrimitive.Description>,
  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
  <AlertDialogPrimitive.Description
    ref={ref}
    className={cn('text-sm leading-6 text-text-tertiary', className)}
    {...props}
  />
))
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName

const actionVariants = cva(
  'inline-flex h-[var(--control-height-md)] items-center justify-center rounded px-[var(--control-padding-x-lg)] text-[length:var(--control-font-size-md)] leading-[var(--control-line-height-md)] font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-border focus-visible:ring-offset-2 focus-visible:ring-offset-bg-base disabled:pointer-events-none disabled:opacity-50 cursor-pointer',
  {
    variants: {
      destructive: {
        true: 'bg-error text-text-on-primary hover:bg-error-hover active:bg-error',
        false: 'bg-bg-highlight text-text-on-primary hover:bg-bg-highlight-hover',
      },
    },
    defaultVariants: { destructive: false },
  }
)

export interface AlertDialogActionProps
  extends React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>,
    VariantProps<typeof actionVariants> {
  destructive?: boolean
}

const AlertDialogAction = React.forwardRef<
  React.ElementRef<typeof AlertDialogPrimitive.Action>,
  AlertDialogActionProps
>(({ className, destructive = false, ...props }, ref) => (
  <AlertDialogPrimitive.Action
    ref={ref}
    className={cn(actionVariants({ destructive }), className)}
    {...props}
  />
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName

const AlertDialogCancel = React.forwardRef<
  React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
  <AlertDialogPrimitive.Cancel
    ref={ref}
    className={cn(
      'inline-flex h-[var(--control-height-md)] items-center justify-center rounded px-[var(--control-padding-x-lg)] text-[length:var(--control-font-size-md)] leading-[var(--control-line-height-md)] font-medium cursor-pointer',
      'bg-transparent text-text-secondary hover:bg-fill-secondary hover:text-text',
      'transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-border focus-visible:ring-offset-2 focus-visible:ring-offset-bg-base',
      className
    )}
    {...props}
  />
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName

export {
  AlertDialog,
  AlertDialogTrigger,
  AlertDialogPortal,
  AlertDialogOverlay,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogFooter,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogAction,
  AlertDialogCancel,
}
export { contentVariants as alertDialogContentVariants, actionVariants as alertDialogActionVariants }
