import type React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import {
  Dialog,
} from "@/components/ui/dialog"
import { X } from "lucide-react"
import { useRsi } from "../hooks/useRsi"
import { useState, useCallback, useRef } from "react"
import { CloseConfirmationDialog } from "./CloseConfirmationDialog"

type Props = {
  children: React.ReactNode
  isOpen: boolean
  onClose: () => void
}

export const ModalWrapper = ({ children, isOpen, onClose }: Props) => {
  const { rtl } = useRsi()
  const [showCloseAlert, setShowCloseAlert] = useState(false)
  // Guard: when we're programmatically closing, don't re-show the alert
  const closingRef = useRef(false)

  // Called after user confirms close in the dialog
  const handleConfirmClose = useCallback(() => {
    // Dismiss the confirmation dialog
    setShowCloseAlert(false)

    // Mark that we're intentionally closing so onOpenChange doesn't re-trigger the alert
    closingRef.current = true

    // Reset scroll positions
    const scrollContainers = document.querySelectorAll('.overflow-auto, .overflow-scroll');
    scrollContainers.forEach(container => {
      if (container instanceof HTMLElement) {
        container.scrollTop = 0;
        container.scrollLeft = 0;
      }
    });

    // Close the main dialog
    onClose();

    // Reset the guard after a tick (after Radix fires onOpenChange)
    requestAnimationFrame(() => {
      closingRef.current = false
    })
  }, [onClose]);

  // Radix fires this when something tries to change the dialog's open state
  // (e.g. focus loss, internal close). We intercept to show our confirmation instead.
  const handleDialogOpenChange = useCallback((open: boolean) => {
    if (!open && !closingRef.current) {
      // Something is trying to close the dialog — show confirmation
      setShowCloseAlert(true)
    }
  }, [])

  return (
    <>
      {/*
        NOTE: We use DialogPrimitive.Portal/Overlay/Content directly instead of the
        shadcn DialogContent component. The shadcn DialogContent internally renders its
        own Portal + Overlay, which would create duplicate portals/overlays and break
        pointer-events for nested Popovers (e.g., select dropdowns).
      */}
      <Dialog open={isOpen} onOpenChange={handleDialogOpenChange} modal>
        <DialogPrimitive.Portal>
          <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-primary/60 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
          <DialogPrimitive.Content
            onEscapeKeyDown={(e) => {
              e.preventDefault()
              setShowCloseAlert(true)
            }}
            onPointerDownOutside={(e) => e.preventDefault()}
            className="fixed left-[50%] top-[50%] z-50 translate-x-[-50%] translate-y-[-50%] w-[calc(100%-2rem)] h-[calc(100%-2rem)] max-w-[100vw] max-h-[100vh] flex flex-col overflow-hidden rounded-lg border bg-background p-0 shadow-lg sm:w-[calc(100%-3rem)] sm:h-[calc(100%-3rem)] md:w-[calc(100%-4rem)] md:h-[calc(100%-4rem)]"
          >
            <button
              type="button"
              className="absolute right-4 top-4 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
              onClick={() => setShowCloseAlert(true)}
            >
              <X className="h-4 w-4" />
              <span className="sr-only">Close</span>
            </button>
            <div dir={rtl ? "rtl" : "ltr"} className="flex-1 overflow-auto">
              {children}
            </div>
          </DialogPrimitive.Content>
        </DialogPrimitive.Portal>
      </Dialog>

      <CloseConfirmationDialog
        open={showCloseAlert}
        onOpenChange={setShowCloseAlert}
        onConfirmClose={handleConfirmClose}
      />
    </>
  )
}
