import React, { useState, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import {
  X,
  ChevronLeft,
  ChevronRight,
  Download,
  ZoomIn,
  ZoomOut,
  RotateCw,
  Maximize2,
  Minimize2,
  Trash2,
  Info,
  Calendar,
  FileImage,
  Tag
} from 'lucide-react';
import { ModelPhoto, PhotoType } from '../types/model';
import { getImageSrc } from '../utils/imagePathUtils';

interface ModelImagePreviewModalProps {
  photos: ModelPhoto[];
  initialIndex: number;
  isOpen: boolean;
  onClose: () => void;
  onDelete?: (photo: ModelPhoto) => void;
  title?: string;
}

/**
 * 模特图片预览模态框组件
 * 支持图片缩放、旋转、删除等操作
 */
export const ModelImagePreviewModal: React.FC<ModelImagePreviewModalProps> = ({
  photos,
  initialIndex,
  isOpen,
  onClose,
  onDelete,
  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);
  const [showInfo, setShowInfo] = useState(false);

  // 重置状态当模态框打开时
  useEffect(() => {
    if (isOpen) {
      setCurrentIndex(initialIndex);
      setZoom(1);
      setRotation(0);
      setIsFullscreen(false);
      setShowInfo(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 'r':
        case 'R':
          handleRotate();
          break;
        case 'f':
        case 'F':
          setIsFullscreen(!isFullscreen);
          break;
        case 'i':
        case 'I':
          setShowInfo(!showInfo);
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, isFullscreen, showInfo]);

  const currentPhoto = photos[currentIndex];

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

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

  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);
  }, []);

  const handleDownload = useCallback(async () => {
    if (!currentPhoto) return;
    
    try {
      // TODO: 实现下载功能
      console.log('下载图片:', currentPhoto.file_path);
    } catch (error) {
      console.error('下载失败:', error);
    }
  }, [currentPhoto]);

  const handleDelete = useCallback(() => {
    if (currentPhoto && onDelete) {
      onDelete(currentPhoto);
    }
  }, [currentPhoto, onDelete]);



  const getPhotoTypeLabel = (photoType: PhotoType): string => {
    switch (photoType) {
      case PhotoType.Portrait:
        return '个人形象照';
      case PhotoType.Commercial:
        return '商业照';
      case PhotoType.Casual:
        return '生活照';
      case PhotoType.FullBody:
        return '全身照';
      case PhotoType.Headshot:
        return '头像照';
      case PhotoType.Artistic:
        return '艺术照';
      default:
        return '其他';
    }
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const formatDate = (dateString: string): string => {
    return new Date(dateString).toLocaleString('zh-CN');
  };



  if (!isOpen || !currentPhoto) return null;

  const imageUrl = getImageSrc(currentPhoto.file_path);

  // 获取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 ${
      isFullscreen ? 'bg-opacity-100' : 'bg-opacity-75'
    }`}>
      {/* 模态框背景 */}
      <div 
        className="absolute inset-0 cursor-pointer"
        onClick={onClose}
      />
      
      {/* 模态框内容 */}
      <div className={`relative bg-white rounded-lg shadow-2xl max-w-7xl max-h-[95vh] w-full mx-4 flex flex-col ${
        isFullscreen ? 'max-w-none max-h-none h-full mx-0 rounded-none' : ''
      }`}>
        {/* 头部工具栏 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 bg-white rounded-t-lg">
          <div className="flex items-center space-x-4">
            <h2 className="text-lg font-semibold text-gray-900">{title}</h2>
            <span className="text-sm text-gray-500">
              {currentIndex + 1} / {photos.length}
            </span>
          </div>
          
          <div className="flex items-center space-x-2">
            {/* 信息按钮 */}
            <button
              onClick={() => setShowInfo(!showInfo)}
              className={`p-2 rounded-lg transition-colors ${
                showInfo ? 'bg-blue-100 text-blue-600' : 'text-gray-600 hover:bg-gray-100'
              }`}
              title="显示信息 (I)"
            >
              <Info className="w-5 h-5" />
            </button>
            

            
            {/* 缩放控制 */}
            <button
              onClick={handleZoomOut}
              className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
              title="缩小 (-)"
            >
              <ZoomOut className="w-5 h-5" />
            </button>
            
            <span className="text-sm text-gray-500 min-w-[4rem] text-center">
              {Math.round(zoom * 100)}%
            </span>
            
            <button
              onClick={handleZoomIn}
              className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
              title="放大 (+)"
            >
              <ZoomIn className="w-5 h-5" />
            </button>
            
            {/* 旋转按钮 */}
            <button
              onClick={handleRotate}
              className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
              title="旋转 (R)"
            >
              <RotateCw className="w-5 h-5" />
            </button>
            
            {/* 全屏按钮 */}
            <button
              onClick={() => setIsFullscreen(!isFullscreen)}
              className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
              title="全屏 (F)"
            >
              {isFullscreen ? <Minimize2 className="w-5 h-5" /> : <Maximize2 className="w-5 h-5" />}
            </button>
            
            {/* 下载按钮 */}
            <button
              onClick={handleDownload}
              className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
              title="下载"
            >
              <Download className="w-5 h-5" />
            </button>
            
            {/* 删除按钮 */}
            {onDelete && (
              <button
                onClick={handleDelete}
                className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                title="删除"
              >
                <Trash2 className="w-5 h-5" />
              </button>
            )}
            
            {/* 关闭按钮 */}
            <button
              onClick={onClose}
              className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
              title="关闭 (Esc)"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* 主要内容区域 */}
        <div className="flex flex-1 overflow-hidden">
          {/* 图片展示区域 */}
          <div className="flex-1 flex items-center justify-center bg-gray-100 overflow-hidden relative">
            {/* 左箭头 */}
            {photos.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={imageUrl}
                alt={currentPhoto.description || currentPhoto.file_name}
                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}
                onLoad={() => setIsLoading(false)}
                onLoadStart={() => setIsLoading(true)}
              />
              
              {isLoading && (
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
                </div>
              )}
            </div>
            
            {/* 右箭头 */}
            {photos.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>
          
          {/* 信息面板 */}
          {showInfo && (
            <div className="w-80 bg-white border-l border-gray-200 p-6 overflow-y-auto">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">图片信息</h3>
              
              <div className="space-y-4">
                {/* 基本信息 */}
                <div>
                  <h4 className="text-sm font-medium text-gray-900 mb-2 flex items-center">
                    <FileImage className="w-4 h-4 mr-1" />
                    基本信息
                  </h4>
                  <div className="space-y-2 text-sm">
                    <div>
                      <span className="text-gray-500">文件名：</span>
                      <span className="text-gray-900">{currentPhoto.file_name}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">文件大小：</span>
                      <span className="text-gray-900">{formatFileSize(currentPhoto.file_size)}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">照片类型：</span>
                      <span className="text-gray-900">{getPhotoTypeLabel(currentPhoto.photo_type)}</span>
                    </div>
                  </div>
                </div>

                {/* 时间信息 */}
                <div>
                  <h4 className="text-sm font-medium text-gray-900 mb-2 flex items-center">
                    <Calendar className="w-4 h-4 mr-1" />
                    时间信息
                  </h4>
                  <div className="space-y-2 text-sm">
                    <div>
                      <span className="text-gray-500">创建时间：</span>
                      <span className="text-gray-900">{formatDate(currentPhoto.created_at)}</span>
                    </div>
                  </div>
                </div>

                {/* 描述 */}
                {currentPhoto.description && (
                  <div>
                    <h4 className="text-sm font-medium text-gray-900 mb-2">描述</h4>
                    <p className="text-sm text-gray-700">{currentPhoto.description}</p>
                  </div>
                )}

                {/* 标签 */}
                {currentPhoto.tags.length > 0 && (
                  <div>
                    <h4 className="text-sm font-medium text-gray-900 mb-2 flex items-center">
                      <Tag className="w-4 h-4 mr-1" />
                      标签
                    </h4>
                    <div className="flex flex-wrap gap-2">
                      {currentPhoto.tags.map((tag, index) => (
                        <span
                          key={index}
                          className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full"
                        >
                          {tag}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
        
        {/* 底部缩略图导航 */}
        {photos.length > 1 && (
          <div className="border-t border-gray-200 p-4 bg-white">
            <div className="flex space-x-2 overflow-x-auto">
              {photos.map((photo, index) => (
                <button
                  key={photo.id}
                  onClick={() => setCurrentIndex(index)}
                  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-200'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <img
                    src={getImageSrc(photo.file_path)}
                    alt={photo.file_name}
                    className="w-full h-full object-cover"
                  />
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>,
    modalRoot
  );
};

export default ModelImagePreviewModal;
