import * as React from 'react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from './dialog'

/**
 * Modal — adapter с @nstart/ui-style API над Radix Dialog. Используется
 * существующим кодом (см. dictionaries.$name.tsx, webhooks, reviews etc.) —
 * упрощает codemod без рефактора каждого callsite.
 *
 * Props mapping:
 *   isOpen → Dialog.open
 *   onClose → Dialog.onOpenChange (false case)
 *   title → DialogTitle children
 *   description → DialogDescription
 *   maxWidth → DialogContent size (mapped: max-w-md→sm, max-w-lg→md, max-w-2xl→lg, max-w-4xl→xl)
 *   children → DialogContent body
 *
 * Новый код может использовать Dialog напрямую — он остаётся exported.
 */

const SIZE_MAP: Record<string, 'sm' | 'md' | 'lg' | 'xl' | 'full'> = {
  'max-w-sm': 'sm',
  'max-w-md': 'sm',
  'max-w-lg': 'md',
  'max-w-xl': 'md',
  'max-w-2xl': 'lg',
  'max-w-3xl': 'lg',
  'max-w-4xl': 'xl',
  'max-w-5xl': 'xl',
  'max-w-6xl': 'full',
}

export type ModalProps = {
  isOpen: boolean
  onClose: () => void
  title?: React.ReactNode
  description?: React.ReactNode
  maxWidth?: string
  size?: 'sm' | 'md' | 'lg' | 'xl' | 'full'
  children?: React.ReactNode
  hideClose?: boolean
  /** Дополнительный className на DialogContent panel (nstart-compat). */
  panelClassName?: string
  /** Дополнительный className на body wrapper (nstart-compat). */
  bodyClassName?: string
}

export function Modal({
  isOpen,
  onClose,
  title,
  description,
  maxWidth,
  size,
  hideClose,
  panelClassName,
  bodyClassName,
  children,
}: ModalProps) {
  const resolved = size ?? (maxWidth ? SIZE_MAP[maxWidth] : undefined) ?? 'md'
  return (
    <Dialog
      open={isOpen}
      onOpenChange={(open) => {
        if (!open) onClose()
      }}
    >
      <DialogContent size={resolved} hideClose={hideClose} className={panelClassName}>
        {(title || description) && (
          <DialogHeader>
            {title && <DialogTitle>{title}</DialogTitle>}
            {description && <DialogDescription>{description}</DialogDescription>}
          </DialogHeader>
        )}
        {bodyClassName ? <div className={bodyClassName}>{children}</div> : children}
      </DialogContent>
    </Dialog>
  )
}
