import React, { useState, useCallback, useEffect } from 'react';
import { createPortal } from 'react-dom';
import {
  X,
  Download,
  ExternalLink,
  ZoomIn,
  ZoomOut,
  RotateCw,
  Calendar,
  MapPin,
  User,
  Shirt,
  AlertCircle,
  ChevronLeft,
  ChevronRight,
  DownloadCloud
} from 'lucide-react';
import { GroundingSource } from '../types/ragGrounding';

/**
 * 图片预览模态框属性接口
 */
interface ImagePreviewModalProps {
  /** 是否显示模态框 */
  isOpen: boolean;
  /** Grounding 来源数据 */
  source: GroundingSource | null;
  /** 关闭回调 */
  onClose: () => void;
  /** 下载回调 */
  onDownload?: (source: GroundingSource) => void;
  /** 所有图片列表 */
  images?: string[];
  /** 当前图片索引 */
  currentIndex?: number;
  /** 导航回调 */
  onNavigate?: (index: number) => void;
}

/**
 * 图片预览模态框组件
 * 支持图片缩放、旋转和详细信息展示
 */
export const ImagePreviewModal: React.FC<ImagePreviewModalProps> = ({
  isOpen,
  source,
  onClose,
  onDownload,
  images = [],
  currentIndex = 0,
  onNavigate
}) => {
  const [imageLoaded, setImageLoaded] = useState(false);
  const [imageError, setImageError] = useState(false);
  const [zoom, setZoom] = useState(1);
  const [rotation, setRotation] = useState(0);
  const [isDownloading, setIsDownloading] = useState(false);

  // 切换到上一张图片
  const handlePrevious = useCallback(() => {
    if (images.length > 1 && onNavigate) {
      const newIndex = currentIndex > 0 ? currentIndex - 1 : images.length - 1;
      onNavigate(newIndex);
    }
  }, [images, currentIndex, onNavigate]);

  // 切换到下一张图片
  const handleNext = useCallback(() => {
    if (images.length > 1 && onNavigate) {
      const newIndex = currentIndex < images.length - 1 ? currentIndex + 1 : 0;
      onNavigate(newIndex);
    }
  }, [images, currentIndex, onNavigate]);

  // 批量下载所有图片
  const handleBatchDownload = useCallback(async () => {
    if (!images.length || !onDownload) return;

    setIsDownloading(true);
    try {
      for (let i = 0; i < images.length; i++) {
        const imageSource: GroundingSource = {
          uri: images[i],
          title: `穿搭图片 ${i + 1}`,
          content: { description: '穿搭生成图片' }
        };
        await onDownload(imageSource);
        // 添加小延迟避免过快下载
        await new Promise(resolve => setTimeout(resolve, 500));
      }
    } catch (error) {
      console.error('批量下载失败:', error);
    } finally {
      setIsDownloading(false);
    }
  }, [images, onDownload]);

  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (!isOpen) return;

      switch (event.key) {
        case 'Escape':
          onClose();
          break;
        case 'ArrowLeft':
          event.preventDefault();
          handlePrevious();
          break;
        case 'ArrowRight':
          event.preventDefault();
          handleNext();
          break;
        case '+':
        case '=':
          event.preventDefault();
          setZoom(prev => Math.min(prev + 0.25, 3));
          break;
        case '-':
          event.preventDefault();
          setZoom(prev => Math.max(prev - 0.25, 0.25));
          break;
        case 'r':
        case 'R':
          event.preventDefault();
          setRotation(prev => prev + 90);
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose, handlePrevious, handleNext]);

  // 重置状态当模态框打开时
  useEffect(() => {
    if (isOpen) {
      setImageLoaded(false);
      setImageError(false);
      setZoom(1);
      setRotation(0);
    }
  }, [isOpen]);

  // 处理键盘事件
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (!isOpen) return;

      switch (event.key) {
        case 'Escape':
          onClose();
          break;
        case '+':
        case '=':
          setZoom(prev => Math.min(prev + 0.25, 3));
          break;
        case '-':
          setZoom(prev => Math.max(prev - 0.25, 0.25));
          break;
        case 'r':
        case 'R':
          setRotation(prev => (prev + 90) % 360);
          break;
      }
    };

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

  // 处理图片加载
  const handleImageLoad = useCallback(() => {
    setImageLoaded(true);
    setImageError(false);
  }, []);

  const handleImageError = useCallback(() => {
    setImageError(true);
    setImageLoaded(false);
  }, []);

  // 处理下载
  const handleDownload = useCallback(async () => {
    if (!onDownload || !source || isDownloading) return;
    
    setIsDownloading(true);
    try {
      await onDownload(source);
    } catch (error) {
      console.error('下载失败:', error);
    } finally {
      setIsDownloading(false);
    }
  }, [onDownload, source, isDownloading]);

  // 缩放控制
  const handleZoomIn = useCallback(() => {
    setZoom(prev => Math.min(prev + 0.25, 3));
  }, []);

  const handleZoomOut = useCallback(() => {
    setZoom(prev => Math.max(prev - 0.25, 0.25));
  }, []);

  const handleRotate = useCallback(() => {
    setRotation(prev => (prev + 90) % 360);
  }, []);

  if (!isOpen || !source) {
    console.log('🖼️ ImagePreviewModal: 不渲染', { isOpen, source });
    return null;
  }

  console.log('🖼️ ImagePreviewModal: 开始渲染', { isOpen, source });

  const imageData = source.content?.text || source.content;
  const imageUri = source.uri;
  const title = source.title || '时尚图片';
  const description = imageData?.description || '';
  const models = imageData?.models || [];
  const environmentTags = imageData?.environment_tags || [];
  const categories = imageData?.categories || [];
  const releaseDate = imageData?.releaseDate;

  // 获取modal-root容器
  const modalRoot = document.getElementById('modal-root');
  if (!modalRoot) {
    console.error('🖼️ Modal root element not found');
    return null;
  }

  console.log('🖼️ Modal root found:', modalRoot);

  const modalContent = (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75">
      {/* 模态框背景 */}
      <div 
        className="absolute inset-0 cursor-pointer"
        onClick={onClose}
      />

      {/* 模态框内容 */}
      <div className="relative bg-white rounded-xl shadow-2xl max-w-6xl max-h-[90vh] w-full mx-4 overflow-hidden">
        {/* 头部工具栏 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 bg-gray-50">
          <div className="flex items-center space-x-3">
            <h2 className="text-lg font-semibold text-gray-900 truncate">{title}</h2>
            {description && (
              <p className="text-sm text-gray-600 truncate max-w-md">{description}</p>
            )}
          </div>
          
          <div className="flex items-center space-x-2">
            {/* 图片导航 */}
            {images.length > 1 && (
              <div className="flex items-center space-x-1 bg-white rounded-lg border border-gray-200 p-1">
                <button
                  onClick={handlePrevious}
                  className="p-1 text-gray-500 hover:text-gray-700 transition-colors"
                  title="上一张 (←)"
                >
                  <ChevronLeft className="w-4 h-4" />
                </button>
                <span className="text-xs text-gray-600 px-2 min-w-[3rem] text-center">
                  {currentIndex + 1}/{images.length}
                </span>
                <button
                  onClick={handleNext}
                  className="p-1 text-gray-500 hover:text-gray-700 transition-colors"
                  title="下一张 (→)"
                >
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            )}

            {/* 缩放控制 */}
            <div className="flex items-center space-x-1 bg-white rounded-lg border border-gray-200 p-1">
              <button
                onClick={handleZoomOut}
                className="p-1 text-gray-500 hover:text-gray-700 transition-colors"
                title="缩小 (-)"
              >
                <ZoomOut className="w-4 h-4" />
              </button>
              <span className="text-xs text-gray-600 px-2 min-w-[3rem] text-center">
                {Math.round(zoom * 100)}%
              </span>
              <button
                onClick={handleZoomIn}
                className="p-1 text-gray-500 hover:text-gray-700 transition-colors"
                title="放大 (+)"
              >
                <ZoomIn className="w-4 h-4" />
              </button>
            </div>

            {/* 旋转按钮 */}
            <button
              onClick={handleRotate}
              className="p-2 text-gray-500 hover:text-gray-700 transition-colors bg-white rounded-lg border border-gray-200"
              title="旋转 (R)"
            >
              <RotateCw className="w-4 h-4" />
            </button>

            {/* 下载按钮 */}
            {onDownload && (
              <>
                <button
                  onClick={handleDownload}
                  disabled={isDownloading}
                  className="p-2 text-gray-500 hover:text-pink-500 transition-colors bg-white rounded-lg border border-gray-200 disabled:opacity-50"
                  title="下载当前图片"
                >
                  <Download className={`w-4 h-4 ${isDownloading ? 'animate-pulse' : ''}`} />
                </button>

                {/* 批量下载按钮 */}
                {images.length > 1 && (
                  <button
                    onClick={handleBatchDownload}
                    disabled={isDownloading}
                    className="p-2 text-gray-500 hover:text-green-500 transition-colors bg-white rounded-lg border border-gray-200 disabled:opacity-50"
                    title={`批量下载所有 ${images.length} 张图片`}
                  >
                    <DownloadCloud className={`w-4 h-4 ${isDownloading ? 'animate-pulse' : ''}`} />
                  </button>
                )}
              </>
            )}

            {/* 外部链接 */}
            {imageUri && (
              <a
                href={imageUri}
                target="_blank"
                rel="noopener noreferrer"
                className="p-2 text-gray-500 hover:text-blue-500 transition-colors bg-white rounded-lg border border-gray-200"
                title="在新窗口打开"
              >
                <ExternalLink className="w-4 h-4" />
              </a>
            )}

            {/* 关闭按钮 */}
            <button
              onClick={onClose}
              className="p-2 text-gray-500 hover:text-gray-700 transition-colors bg-white rounded-lg border border-gray-200"
              title="关闭 (Esc)"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* 主要内容区域 */}
        <div className="flex h-[calc(90vh-5rem)]">
          {/* 图片展示区域 */}
          <div className="flex-1 flex items-center justify-center bg-gray-100 overflow-hidden">
            {imageUri && !imageError ? (
              <div className="relative w-full h-full flex items-center justify-center">
                <img
                  src={imageUri}
                  alt={description || title}
                  className={`max-w-full max-h-full object-contain transition-all duration-300 ${
                    imageLoaded ? 'opacity-100' : 'opacity-0'
                  }`}
                  style={{
                    transform: `scale(${zoom}) rotate(${rotation}deg)`,
                    transformOrigin: 'center'
                  }}
                  onLoad={handleImageLoad}
                  onError={handleImageError}
                />
                {!imageLoaded && (
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-pink-500"></div>
                  </div>
                )}
              </div>
            ) : (
              <div className="text-center text-gray-400">
                <AlertCircle className="w-16 h-16 mx-auto mb-4" />
                <p className="text-lg">图片无法加载</p>
              </div>
            )}
          </div>

          {/* 信息侧边栏 */}
          <div className="w-80 bg-gray-50 border-l border-gray-200 overflow-y-auto">
            <div className="p-4 space-y-4">
              {/* 基本信息 */}
              <div>
                <h3 className="text-sm font-medium text-gray-900 mb-2">基本信息</h3>
                <div className="space-y-2">
                  {description && (
                    <p className="text-sm text-gray-600">{description}</p>
                  )}
                  {releaseDate && (
                    <div className="flex items-center space-x-2">
                      <Calendar className="w-4 h-4 text-gray-400" />
                      <span className="text-sm text-gray-600">
                        {new Date(releaseDate).toLocaleDateString('zh-CN')}
                      </span>
                    </div>
                  )}
                </div>
              </div>

              {/* 环境标签 */}
              {environmentTags.length > 0 && (
                <div>
                  <h3 className="text-sm font-medium text-gray-900 mb-2 flex items-center">
                    <MapPin className="w-4 h-4 mr-1" />
                    环境场景
                  </h3>
                  <div className="flex flex-wrap gap-1">
                    {environmentTags.map((tag: string, index: number) => (
                      <span
                        key={index}
                        className="px-2 py-1 bg-blue-50 text-blue-600 text-xs rounded-full"
                      >
                        {tag}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* 服装类别 */}
              {categories.length > 0 && (
                <div>
                  <h3 className="text-sm font-medium text-gray-900 mb-2 flex items-center">
                    <Shirt className="w-4 h-4 mr-1" />
                    服装类别
                  </h3>
                  <div className="flex flex-wrap gap-1">
                    {categories.map((category: string, index: number) => (
                      <span
                        key={index}
                        className="px-2 py-1 bg-pink-50 text-pink-600 text-xs rounded-full"
                      >
                        {category}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* 模特信息 */}
              {models.length > 0 && (
                <div>
                  <h3 className="text-sm font-medium text-gray-900 mb-2 flex items-center">
                    <User className="w-4 h-4 mr-1" />
                    模特信息 ({models.length})
                  </h3>
                  <div className="space-y-2">
                    {models.slice(0, 3).map((model: any, index: number) => (
                      <div key={index} className="p-2 bg-white rounded border border-gray-200">
                        <p className="text-xs text-gray-600 mb-1">{model.position}</p>
                        <p className="text-xs text-gray-800">{model.style_description}</p>
                      </div>
                    ))}
                    {models.length > 3 && (
                      <p className="text-xs text-gray-500">还有 {models.length - 3} 位模特...</p>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, modalRoot);
};

export default ImagePreviewModal;
