import React, { useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import ModalOverlay from './ModalOverlay';
import ModalDialog from './ModalDialog';
import ModalContent from './ModalContent';

interface VariationModalProps {
  isOpen: boolean;
  onClose: () => void;
  data?: any;
}

const VariationModal: React.FC<VariationModalProps> = ({
  isOpen,
  onClose,
  data
}) => {
  // 点击外部关闭弹窗
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleEscape);
      document.body.style.overflow = 'hidden';
    }

    return () => {
      document.removeEventListener('keydown', handleEscape);
      document.body.style.overflow = 'unset';
    };
  }, [isOpen, onClose]);

  return (
    <AnimatePresence>
      {isOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          {/* 遮罩层 */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.3 }}
          >
            <ModalOverlay onClick={onClose} />
          </motion.div>

          {/* 弹窗容器 */}
          <motion.div
            initial={{ opacity: 0, scale: 0.8, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.8, y: 20 }}
            transition={{
              duration: 0.4,
              ease: "easeOut"
            }}
            className="relative z-10"
          >
            <ModalDialog>
              {/* 弹窗内容 */}
              <ModalContent data={data} onClose={onClose} />
            </ModalDialog>
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );
};

export default VariationModal;