import React, { useState, useEffect, useCallback } from 'react';
import {
  X,
  ChevronLeft,
  ChevronRight,
  Download,
  ZoomIn,
  ZoomOut,
  RotateCw,
  Maximize2,
  Minimize2,
  Copy,
  ExternalLink
} from 'lucide-react';

interface ImageGalleryModalProps {
  images: string[];
  initialIndex: number;
  isOpen: boolean;
  onClose: () => void;
  title?: string;
}

export const ImageGalleryModal: React.FC<ImageGalleryModalProps> = ({
  images,
  initialIndex,
  isOpen,
  onClose,
  title = "图片预览"
}) => {
  const [currentIndex, setCurrentIndex] = useState(initialIndex);
  const [zoom, setZoom] = useState(1);
  const [rotation, setRotation] = useState(0);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

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

  // 键盘快捷键
  useEffect(() => {
    if (!isOpen) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      switch (e.key) {
        case 'Escape':
          onClose();
          break;
        case 'ArrowLeft':
          goToPrevious();
          break;
        case 'ArrowRight':
          goToNext();
          break;
        case '+':
        case '=':
          handleZoomIn();
          break;
        case '-':
          handleZoomOut();
          break;
        case '0':
          setZoom(1);
          break;
        case 'r':
        case 'R':
          handleRotate();
          break;
        case 'f':
        case 'F':
          setIsFullscreen(!isFullscreen);
          break;
      }
    };

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

  const goToPrevious = useCallback(() => {
    setCurrentIndex(prev => prev > 0 ? prev - 1 : images.length - 1);
    setZoom(1);
    setRotation(0);
  }, [images.length]);

  const goToNext = useCallback(() => {
    setCurrentIndex(prev => prev < images.length - 1 ? prev + 1 : 0);
    setZoom(1);
    setRotation(0);
  }, [images.length]);

  const handleZoomIn = () => {
    setZoom(prev => Math.min(prev + 0.25, 3));
  };

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

  const handleRotate = () => {
    setRotation(prev => (prev + 90) % 360);
  };

  const handleDownload = async () => {
    if (!images[currentIndex]) return;
    
    setIsLoading(true);
    try {
      const response = await fetch(images[currentIndex]);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      
      const link = document.createElement('a');
      link.href = url;
      link.download = `generated-image-${currentIndex + 1}.jpg`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('下载失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCopyUrl = async () => {
    if (!images[currentIndex]) return;
    
    try {
      await navigator.clipboard.writeText(images[currentIndex]);
      // 这里可以添加一个临时的成功提示
    } catch (error) {
      console.error('复制失败:', error);
    }
  };

  const handleOpenInNewTab = () => {
    if (!images[currentIndex]) return;
    window.open(images[currentIndex], '_blank');
  };

  if (!isOpen || images.length === 0) return null;

  const currentImage = images[currentIndex];

  return (
    <div className="fixed inset-0 z-50 bg-black bg-opacity-95 flex items-center justify-center">
      {/* 背景遮罩 */}
      <div 
        className="absolute inset-0 cursor-pointer"
        onClick={onClose}
      />
      
      {/* 主容器 */}
      <div className={`relative ${isFullscreen ? 'w-full h-full' : 'max-w-7xl max-h-[95vh] w-full h-full'} flex flex-col`}>
        
        {/* 顶部工具栏 */}
        <div className="relative z-10 bg-black bg-opacity-60 backdrop-blur-sm p-4 flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <h3 className="text-white text-lg font-medium">{title}</h3>
            <span className="text-gray-300 text-sm">
              {currentIndex + 1} / {images.length}
            </span>
          </div>
          
          <div className="flex items-center space-x-2">
            {/* 缩放控制 */}
            <button
              onClick={handleZoomOut}
              className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded-lg transition-colors"
              title="缩小 (-)"
            >
              <ZoomOut className="w-5 h-5" />
            </button>
            
            <span className="text-white text-sm min-w-[60px] text-center">
              {Math.round(zoom * 100)}%
            </span>
            
            <button
              onClick={handleZoomIn}
              className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded-lg transition-colors"
              title="放大 (+)"
            >
              <ZoomIn className="w-5 h-5" />
            </button>
            
            {/* 旋转 */}
            <button
              onClick={handleRotate}
              className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded-lg transition-colors"
              title="旋转 (R)"
            >
              <RotateCw className="w-5 h-5" />
            </button>
            
            {/* 全屏切换 */}
            <button
              onClick={() => setIsFullscreen(!isFullscreen)}
              className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded-lg transition-colors"
              title="全屏 (F)"
            >
              {isFullscreen ? <Minimize2 className="w-5 h-5" /> : <Maximize2 className="w-5 h-5" />}
            </button>
            
            {/* 复制链接 */}
            <button
              onClick={handleCopyUrl}
              className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded-lg transition-colors"
              title="复制图片链接"
            >
              <Copy className="w-5 h-5" />
            </button>
            
            {/* 新标签页打开 */}
            <button
              onClick={handleOpenInNewTab}
              className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded-lg transition-colors"
              title="在新标签页打开"
            >
              <ExternalLink className="w-5 h-5" />
            </button>
            
            {/* 下载 */}
            <button
              onClick={handleDownload}
              disabled={isLoading}
              className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded-lg transition-colors disabled:opacity-50"
              title="下载图片"
            >
              <Download className={`w-5 h-5 ${isLoading ? 'animate-pulse' : ''}`} />
            </button>
            
            {/* 关闭 */}
            <button
              onClick={onClose}
              className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded-lg transition-colors"
              title="关闭 (Esc)"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>
        
        {/* 图片容器 */}
        <div className="flex-1 relative overflow-hidden flex items-center justify-center">
          {/* 左箭头 */}
          {images.length > 1 && (
            <button
              onClick={goToPrevious}
              className="absolute left-4 z-10 p-3 bg-black bg-opacity-60 text-white rounded-full hover:bg-opacity-80 transition-all shadow-lg"
              title="上一张 (←)"
            >
              <ChevronLeft className="w-6 h-6" />
            </button>
          )}
          
          {/* 图片 */}
          <div className="relative max-w-full max-h-full flex items-center justify-center p-4">
            <img
              src={currentImage}
              alt={`预览图片 ${currentIndex + 1}`}
              className="max-w-full max-h-full object-contain transition-transform duration-200 cursor-grab active:cursor-grabbing shadow-2xl"
              style={{
                transform: `scale(${zoom}) rotate(${rotation}deg)`,
                transformOrigin: 'center'
              }}
              draggable={false}
            />
          </div>
          
          {/* 右箭头 */}
          {images.length > 1 && (
            <button
              onClick={goToNext}
              className="absolute right-4 z-10 p-3 bg-black bg-opacity-60 text-white rounded-full hover:bg-opacity-80 transition-all shadow-lg"
              title="下一张 (→)"
            >
              <ChevronRight className="w-6 h-6" />
            </button>
          )}
        </div>
        
        {/* 底部缩略图导航 */}
        {images.length > 1 && (
          <div className="relative z-10 bg-black bg-opacity-60 backdrop-blur-sm p-4">
            <div className="flex justify-center space-x-2 overflow-x-auto max-w-full">
              {images.map((image, index) => (
                <button
                  key={index}
                  onClick={() => {
                    setCurrentIndex(index);
                    setZoom(1);
                    setRotation(0);
                  }}
                  className={`flex-shrink-0 w-16 h-16 rounded-lg overflow-hidden border-2 transition-all ${
                    index === currentIndex 
                      ? 'border-blue-500 ring-2 ring-blue-500 ring-opacity-50 scale-110' 
                      : 'border-gray-600 hover:border-gray-400 hover:scale-105'
                  }`}
                >
                  <img
                    src={image}
                    alt={`缩略图 ${index + 1}`}
                    className="w-full h-full object-cover"
                  />
                </button>
              ))}
            </div>
          </div>
        )}
        
        {/* 快捷键提示 */}
        <div className="absolute bottom-4 left-4 text-gray-300 text-xs space-y-1 bg-black bg-opacity-60 p-3 rounded-lg backdrop-blur-sm">
          <div className="font-medium text-gray-200 mb-1">快捷键:</div>
          <div>← → 切换图片</div>
          <div>+ - 缩放</div>
          <div>R 旋转</div>
          <div>F 全屏</div>
          <div>Esc 关闭</div>
        </div>
      </div>
    </div>
  );
};
