import React, { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { X } from 'lucide-react';

interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  title?: string;
  subtitle?: string;
  icon?: React.ReactNode;
  size?: 'sm' | 'md' | 'lg' | 'xl' | 'full';
  variant?: 'default' | 'danger' | 'success' | 'warning' | 'info';
  children: React.ReactNode;
  showCloseButton?: boolean;
  closeOnBackdropClick?: boolean;
  closeOnEscape?: boolean;
  className?: string;
  headerClassName?: string;
  contentClassName?: string;
}

/**
 * 统一的弹框组件
 * 支持多种尺寸、变体和交互方式
 */
export const Modal: React.FC<ModalProps> = ({
  isOpen,
  onClose,
  title,
  subtitle,
  icon,
  size = 'md',
  variant = 'default',
  children,
  showCloseButton = true,
  closeOnBackdropClick = true,
  closeOnEscape = true,
  className = '',
  headerClassName = '',
  contentClassName = '',
}) => {
  const modalRef = useRef<HTMLDivElement>(null);

  // ESC 键关闭
  useEffect(() => {
    if (!isOpen || !closeOnEscape) return;

    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [isOpen, closeOnEscape, onClose]);

  // 禁用背景滚动 - 简化版本
  useEffect(() => {
    if (isOpen) {
      // 保存当前滚动位置
      const scrollY = window.scrollY;

      // 禁用body滚动并保持滚动位置
      document.body.style.overflow = 'hidden';
      document.body.style.position = 'fixed';
      document.body.style.top = `-${scrollY}px`;
      document.body.style.width = '100%';

      // 防止iOS Safari的橡皮筋效果
      document.documentElement.style.overflow = 'hidden';

      return () => {
        // 恢复滚动状态
        document.body.style.overflow = '';
        document.body.style.position = '';
        document.body.style.top = '';
        document.body.style.width = '';
        document.documentElement.style.overflow = '';

        // 恢复滚动位置
        window.scrollTo(0, scrollY);
      };
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const getSizeClasses = () => {
    const sizeMap = {
      sm: 'w-full max-w-md',
      md: 'w-full max-w-lg',
      lg: 'w-full max-w-2xl',
      xl: 'w-full max-w-4xl',
      full: 'w-full max-w-7xl',
    };
    return sizeMap[size];
  };

  const getVariantClasses = () => {
    const variantMap = {
      default: 'from-primary-50 via-blue-50 to-primary-50 border-primary-200',
      danger: 'from-red-50 via-red-50 to-red-100 border-red-200',
      success: 'from-green-50 via-green-50 to-green-100 border-green-200',
      warning: 'from-yellow-50 via-yellow-50 to-yellow-100 border-yellow-200',
      info: 'from-blue-50 via-blue-50 to-blue-100 border-blue-200',
    };
    return variantMap[variant];
  };

  const getIconColor = () => {
    const colorMap = {
      default: 'from-primary-500 to-primary-600',
      danger: 'from-red-500 to-red-600',
      success: 'from-green-500 to-green-600',
      warning: 'from-yellow-500 to-yellow-600',
      info: 'from-blue-500 to-blue-600',
    };
    return colorMap[variant];
  };

  const handleBackdropClick = (e: React.MouseEvent) => {
    if (closeOnBackdropClick && e.target === e.currentTarget) {
      onClose();
    }
  };

  // 获取 Modal 根容器
  const getModalRoot = () => {
    return document.getElementById('modal-root') || document.body;
  };

  const modalContent = (
    <div
      className="modal-overlay-container"
      onClick={handleBackdropClick}
    >
      {/* 背景遮罩 - 确保占满整个屏幕，不受父级滚动影响 */}
      <div className="modal-backdrop-fixed" />

      {/* 弹框容器 */}
      <div
        ref={modalRef}
        className={`modal-container ${size === 'xl' || size === 'full' ? 'large' : ''} ${getSizeClasses()} max-h-[90vh] animate-modal-scale-in relative z-10 ${className}`}
      >
        {/* 头部 */}
        {(title || subtitle || icon || showCloseButton) && (
          <div className={`flex items-center justify-between p-6 bg-gradient-to-r ${getVariantClasses()} border-b ${headerClassName}`}>
            <div className="flex items-center gap-4 flex-1 min-w-0">
              {icon && (
                <div className={`w-12 h-12 bg-gradient-to-br ${getIconColor()} rounded-xl flex items-center justify-center shadow-sm`}>
                  {icon}
                </div>
              )}
              <div className="flex-1 min-w-0">
                {title && (
                  <h2 className="text-xl font-bold text-gray-900 truncate">
                    {title}
                  </h2>
                )}
                {subtitle && (
                  <p className="text-sm text-gray-600 mt-1">
                    {subtitle}
                  </p>
                )}
              </div>
            </div>
            {showCloseButton && (
              <button
                onClick={onClose}
                className="ml-4 p-2 text-gray-400 hover:text-gray-600 hover:bg-white hover:shadow-sm rounded-lg transition-all duration-200 flex-shrink-0"
              >
                <X className="w-5 h-5" />
              </button>
            )}
          </div>
        )}

        {/* 内容 */}
        <div className={`modal-content-scroll ${contentClassName}`}>
          {children}
        </div>
      </div>
    </div>
  );

  // 使用 Portal 渲染到 App.tsx 中的 modal-root 容器
  return createPortal(modalContent, getModalRoot());
};

// 预设的弹框配置
export const ModalPresets = {
  // 确认对话框
  confirm: {
    size: 'sm' as const,
    variant: 'default' as const,
    closeOnBackdropClick: false,
  },

  // 危险操作确认
  danger: {
    size: 'sm' as const,
    variant: 'danger' as const,
    closeOnBackdropClick: false,
  },

  // 表单弹框
  form: {
    size: 'md' as const,
    variant: 'default' as const,
    closeOnBackdropClick: true,
  },

  // 详情查看
  detail: {
    size: 'lg' as const,
    variant: 'default' as const,
    closeOnBackdropClick: true,
  },

  // 全屏弹框
  fullscreen: {
    size: 'full' as const,
    variant: 'default' as const,
    closeOnBackdropClick: false,
  },
};
