import * as Dialog from '@radix-ui/react-dialog'
import { Button } from '@/components/ui/button'
import { ReactNode } from 'react'
import { CloseIcon } from '../icons/form-icon'
import { motion, AnimatePresence } from 'framer-motion'

interface ModalRadixProps {
  open: boolean
  onClose: () => void
  children: ReactNode
  contentClassName?: string
  closeButtonClassName?: string
}

export const ModalRadix: React.FC<ModalRadixProps> = ({
  open,
  onClose,
  children,
  contentClassName,
  closeButtonClassName,
}) => {
  return (
    <Dialog.Root open={open} onOpenChange={(v) => !v && onClose()}>
      <AnimatePresence>
        {open && (
          <Dialog.Portal forceMount>
            <Dialog.Overlay asChild>
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.4, ease: [0.4, 0, 0.2, 1] }}
                className="fixed inset-0 z-[9999]"
                style={{
                  background: '#05050599',
                  backdropFilter: 'blur(18px)',
                  WebkitBackdropFilter: 'blur(18px)',
                }}
              />
            </Dialog.Overlay>
            <Dialog.Content asChild onPointerDownOutside={onClose} onInteractOutside={onClose}>
              <motion.div
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.95 }}
                transition={{ duration: 0.28, ease: [0.4, 0, 0.2, 1] }}
                className={[
                  'fixed z-[10000] left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-full px-4 tablet:px-[40px] max-h-screen ',
                  contentClassName,
                ]
                  .filter(Boolean)
                  .join(' ')}
              >
                <Dialog.Title className="sr-only">Contact Dialog</Dialog.Title>
                <div className="relative w-fit mx-auto flex flex-col gap-4">
                  <Dialog.Close asChild>
                    <Button
                      className={[
                        'z-10 text-[#FCFCFC] hover:text-primary transition-colors w-fit self-end',
                        closeButtonClassName,
                      ]
                        .filter(Boolean)
                        .join(' ')}
                      variant="icon-only"
                      aria-label="Close"
                      iconOnly
                      sizes='icon-btn-sm md:icon-btn-md'
                      icon={<CloseIcon className="w-[10px] h-[10px] md:w-[14px] md:h-[14px]"  />}
                    />
                  </Dialog.Close>
                  {children}
                </div>
              </motion.div>
            </Dialog.Content>
          </Dialog.Portal>
        )}
      </AnimatePresence>
    </Dialog.Root>
  )
}

export default ModalRadix
