'use client'

import * as Dialog from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import { type ReactNode } from 'react'
import { adminPortalContainer } from '../../lib/portal-container.js'

export interface ModalProps {
  open: boolean
  onClose: () => void
  title: string
  children: ReactNode
  actions?: ReactNode
  /**
   * Accessible description for the dialog, announced after the title. Optional —
   * omit when the body content is self-explanatory.
   */
  description?: string
}

/**
 * The canonical admin modal. Built on Radix `Dialog`, which provides the
 * accessibility contract for free: focus is trapped while open and restored to
 * the trigger on close, Escape and overlay-click dismiss, the surface is
 * exposed as `role="dialog"` + `aria-modal`, and the title/description are wired
 * via `aria-labelledby`/`aria-describedby`.
 *
 * The portal mounts inside `.actuate-admin` (see `adminPortalContainer`) so the
 * dialog inherits theme tokens and dark mode instead of rendering unstyled on
 * `document.body`.
 */
export function Modal({ open, onClose, title, children, actions, description }: ModalProps) {
  return (
    <Dialog.Root open={open} onOpenChange={(next) => !next && onClose()}>
      <Dialog.Portal container={adminPortalContainer()}>
        <Dialog.Overlay className="fixed inset-0 z-60 bg-black/50" />
        <Dialog.Content className="bg-card text-card-foreground border-border fixed top-1/2 left-1/2 z-60 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-lg border shadow-xl focus:outline-none">
          <div className="border-border flex items-center justify-between border-b px-6 py-4">
            <Dialog.Title className="text-foreground text-lg font-medium">{title}</Dialog.Title>
            <Dialog.Close asChild>
              <button
                type="button"
                aria-label="Close dialog"
                className="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring rounded-md p-1 transition-colors focus-visible:ring-2 focus-visible:outline-none"
              >
                <X className="h-4 w-4" aria-hidden />
              </button>
            </Dialog.Close>
          </div>
          {description && (
            <Dialog.Description className="text-muted-foreground px-6 pt-4 text-sm">
              {description}
            </Dialog.Description>
          )}
          <div className="px-6 py-4">{children}</div>
          {actions && (
            <div className="border-border flex justify-end gap-2 border-t px-6 py-4">{actions}</div>
          )}
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  )
}
