import React, { useEffect } from 'react';
import { createPortal } from 'react-dom';
import { X, Upload } from 'lucide-react';
import { PhotoType } from '../types/model';
import { ModelImageUploader } from './ModelImageUploader';

interface ModelImageUploadModalProps {
  isOpen: boolean;
  onClose: () => void;
  onUpload: (imagePaths: string[], photoType: PhotoType) => Promise<void>;
  isUploading?: boolean;
}

/**
 * 模特图片上传Modal组件
 * 使用Portal渲染到modal-root容器，避免复杂容器结构影响
 */
export const ModelImageUploadModal: React.FC<ModelImageUploadModalProps> = ({
  isOpen,
  onClose,
  onUpload,
  isUploading = false
}) => {
  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown);
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
    }

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

  // 处理上传完成
  const handleUploadComplete = async (imagePaths: string[], photoType: PhotoType) => {
    try {
      await onUpload(imagePaths, photoType);
      onClose(); // 上传成功后关闭Modal
    } catch (error) {
      console.error('上传失败:', error);
      // 不关闭Modal，让用户看到错误信息
    }
  };

  if (!isOpen) return null;

  // 获取modal-root容器
  const modalRoot = document.getElementById('modal-root');
  if (!modalRoot) return null;

  // 使用Portal渲染到modal-root容器
  return createPortal(
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
      {/* 模态框背景 */}
      <div 
        className="absolute inset-0 cursor-pointer"
        onClick={onClose}
      />
      
      {/* 模态框内容 */}
      <div className="relative bg-white rounded-2xl shadow-2xl max-w-2xl max-h-[90vh] w-full mx-4 flex flex-col overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-xl flex items-center justify-center">
              <Upload className="w-6 h-6 text-white" />
            </div>
            <div>
              <h2 className="text-xl font-bold text-gray-900">上传模特照片</h2>
              <p className="text-sm text-gray-600">选择并上传模特的个人形象照片</p>
            </div>
          </div>
          
          <button
            onClick={onClose}
            disabled={isUploading}
            className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            title="关闭 (Esc)"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* 主要内容区域 */}
        <div className="flex-1 overflow-y-auto p-6">
          <ModelImageUploader
            onImagesSelect={handleUploadComplete}
            isUploading={isUploading}
            maxFiles={20}
          />
        </div>

        {/* 底部提示 */}
        <div className="p-6 border-t border-gray-200 bg-gray-50">
          <div className="text-sm text-gray-600">
            <p className="mb-2">
              <span className="font-medium">上传提示：</span>
            </p>
            <ul className="space-y-1 text-xs">
              <li>• 支持 PNG、JPG、JPEG、GIF、BMP、WebP 格式</li>
              <li>• 建议上传高质量的个人形象照片</li>
              <li>• 照片将用于AI视频生成和穿搭图片生成</li>
              <li>• 一次最多可上传 20 张照片</li>
            </ul>
          </div>
        </div>
      </div>
    </div>,
    modalRoot
  );
};

export default ModelImageUploadModal;
