import * as React from 'react'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import { cn } from '@/lib/utils'

/**
 * Radix Dialog — modal в shadcn-стиле. Заменяет {@code @nstart/ui} Modal.
 *
 * Использование:
 * <pre>
 * <Dialog open={open} onOpenChange={setOpen}>
 *   <DialogContent size="md">
 *     <DialogHeader>
 *       <DialogTitle>Создать запись</DialogTitle>
 *       <DialogDescription>Описание формы</DialogDescription>
 *     </DialogHeader>
 *     <div className="…body…" />
 *     <DialogFooter>
 *       <Button variant="secondary" onClick={() => setOpen(false)}>Отмена</Button>
 *       <Button>Сохранить</Button>
 *     </DialogFooter>
 *   </DialogContent>
 * </Dialog>
 * </pre>
 *
 * Default size — 560px (handoff Create-dict). Variants: sm 440px, md 560px,
 * lg 720px, xl 880px, full (mobile fullscreen).
 */
export const Dialog = DialogPrimitive.Root
export const DialogTrigger = DialogPrimitive.Trigger
export const DialogPortal = DialogPrimitive.Portal
export const DialogClose = DialogPrimitive.Close

export const DialogOverlay = React.forwardRef<
  React.ElementRef<typeof DialogPrimitive.Overlay>,
  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(function DialogOverlay({ className, ...props }, ref) {
  return (
    <DialogPrimitive.Overlay
      ref={ref}
      className={cn(
        'fixed inset-0 z-50 bg-black/40 backdrop-blur-[1px]',
        'data-[state=open]:animate-in data-[state=closed]:animate-out',
        'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
        className,
      )}
      {...props}
    />
  )
})

// Mobile <880px = fullscreen (per handoff line 465); ≥880px = centered с max-w.
// Используем arbitrary `min-[880px]:` (Tailwind v4 inline breakpoint) для точной
// границы — handoff specifically wants 880, не стандартный md (768) или lg (1024).
const SIZE_CLASSES: Record<string, string> = {
  sm: 'min-[880px]:max-w-[440px]',
  md: 'min-[880px]:max-w-[560px]',
  lg: 'min-[880px]:max-w-[720px]',
  xl: 'min-[880px]:max-w-[880px]',
  full: 'min-[880px]:max-w-[920px]',
}

export type DialogContentProps = React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
  size?: keyof typeof SIZE_CLASSES
  hideClose?: boolean
}

export const DialogContent = React.forwardRef<
  React.ElementRef<typeof DialogPrimitive.Content>,
  DialogContentProps
>(function DialogContent({ className, children, size = 'md', hideClose, ...props }, ref) {
  return (
    <DialogPortal>
      <DialogOverlay />
      <DialogPrimitive.Content
        ref={ref}
        className={cn(
          'fixed z-50 grid gap-4 border border-line bg-surface p-6 shadow-2xl duration-200',
          // Centered modal — left/top 50% + translate.  В <880px mode пользуем
          // max-width 95vw чтобы modal не упирался в edges (вместо fullscreen
          // inset-0 который конфликтовал с left-1/2 → modal off-screen).
          'left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2',
          'w-[95vw] max-h-[95vh] overflow-y-auto rounded-lg',
          'data-[state=open]:animate-in data-[state=closed]:animate-out',
          'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
          'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
          SIZE_CLASSES[size],
          className,
        )}
        {...props}
      >
        {children}
        {!hideClose && (
          <DialogPrimitive.Close
            aria-label="Закрыть"
            className="absolute right-3 top-3 rounded-sm p-1 text-mute hover:text-ink hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring transition-colors"
          >
            <X size={16} strokeWidth={2.25} />
          </DialogPrimitive.Close>
        )}
      </DialogPrimitive.Content>
    </DialogPortal>
  )
})

export function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
  return <div className={cn('flex flex-col space-y-1.5 pr-8', className)} {...props} />
}

export function DialogFooter({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
  return (
    <div
      className={cn(
        'flex flex-col-reverse gap-2 sm:flex-row sm:justify-end pt-2 border-t border-line-2',
        className,
      )}
      {...props}
    />
  )
}

export const DialogTitle = React.forwardRef<
  React.ElementRef<typeof DialogPrimitive.Title>,
  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(function DialogTitle({ className, ...props }, ref) {
  return (
    <DialogPrimitive.Title
      ref={ref}
      className={cn('text-title-xl text-ink', className)}
      {...props}
    />
  )
})

export const DialogDescription = React.forwardRef<
  React.ElementRef<typeof DialogPrimitive.Description>,
  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(function DialogDescription({ className, ...props }, ref) {
  return (
    <DialogPrimitive.Description
      ref={ref}
      className={cn('text-body text-ink-2', className)}
      {...props}
    />
  )
})
