import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';

type ModalProps = {
  opened: boolean;
  onClose: () => void;
  children: React.ReactNode;
  className?: string;
};

const Modal = ({ opened, onClose, children, className = '' }: ModalProps) => {
  const [mounted, setMounted] = useState(opened);
  const [show, setShow] = useState(false);

  useEffect(() => {
    if (opened) {
      setMounted(true);
      requestAnimationFrame(() => setShow(true));
    } else {
      setShow(false);
      const t = setTimeout(() => setMounted(false), 180);
      return () => clearTimeout(t);
    }
  }, [opened]);

  useEffect(() => {
    if (!opened) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [opened, onClose]);

  if (!mounted) return null;

  const node = (
    <div className="fixed inset-0 z-[300] flex items-center justify-center p-4">
      <div
        className={`absolute inset-0 bg-black/50 transition-opacity duration-200 ${
          show ? 'opacity-100' : 'opacity-0'
        }`}
        onClick={onClose}
      />
      <div
        className={`relative z-[1] mx-auto box-border min-w-0 w-full max-w-[400px] shrink-0 rounded-2xl bg-[var(--tg-bg)]
          shadow-2xl overflow-hidden
          transition-all duration-200 ${className}
          ${show ? 'opacity-100 scale-100' : 'opacity-0 scale-95'}
        `}
      >
        {children}
      </div>
    </div>
  );

  return createPortal(node, document.body);
};

export default Modal;
