"use client"

import * as React from "react"
import { createPortal } from "react-dom"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
import i18n from "@/lib/i18n";

type ModalProps = {
  open: boolean
  onClose: () => void
  title: string
  description?: string
  size?: "sm" | "md" | "lg"
  children: React.ReactNode
  footer?: React.ReactNode
  overflowVisible?: boolean
}

export function Modal({ open, onClose, title, description, size = "md", children, footer, overflowVisible = false }: ModalProps) {
  const [mounted, setMounted] = React.useState(false)

  React.useEffect(() => {
    setMounted(true)
  }, [])

  React.useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose()
    }
    document.addEventListener("keydown", onKey)
    document.body.style.overflow = "hidden"
    return () => {
      document.removeEventListener("keydown", onKey)
      document.body.style.overflow = ""
    }
  }, [open, onClose])

  if (!mounted || !open) return null

  return createPortal(
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4" dir="rtl">
      <div
        className="absolute inset-0 bg-black/40 backdrop-blur-sm"
        onClick={onClose}
        aria-hidden="true"
      />
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="modal-title"
        className={cn(
          "relative w-full rounded-xl border border-border bg-card shadow-2xl",
          !overflowVisible && "overflow-hidden",
          size === "sm" && "max-w-md",
          size === "md" && "max-w-lg",
          size === "lg" && "max-w-3xl",
        )}
      >
        <div className={cn(
          "flex items-start justify-between gap-4 border-b border-border bg-muted/40 px-5 py-4",
          !overflowVisible && "rounded-t-xl"
        )}>
          <div>
            <h2 id="modal-title" className="text-base font-semibold text-foreground">
              {title}
            </h2>
            {description ? <p className="mt-1 text-sm text-muted-foreground">{description}</p> : null}
          </div>
          <button
            type="button"
            onClick={onClose}
            className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
            aria-label={i18n.t('components.ui.modal.text_1')}
          >
            <X className="h-4 w-4" />
          </button>
        </div>
        <div className="px-5 py-5">{children}</div>
        {footer ? (
          <div className={cn(
            "flex items-center justify-start gap-2 border-t border-border bg-muted/30 px-5 py-3",
            !overflowVisible && "rounded-b-xl"
          )}>
            {footer}
          </div>
        ) : null}
      </div>
    </div>,
    document.body,
  )
}

export function ModalActions({ children }: { children: React.ReactNode }) {
  return <div className="flex items-center justify-start gap-2">{children}</div>
}
