import React, { useState, useCallback } from 'react';
import {
  Trash2,
  Clock,
  CheckCircle,
  XCircle,
  Loader,
  Grid3X3,
  List,
  Search,
  Calendar,
  Sparkles,
  Eye,
  RotateCcw
} from 'lucide-react';
import { OutfitImageRecord, OutfitImageStatus } from '../types/outfitImage';
import { DeleteConfirmDialog } from './DeleteConfirmDialog';
import { getImageSrc } from '../utils/imagePathUtils';
import { ImagePreviewModal } from './ImagePreviewModal';
import { GroundingSource } from '../types/ragGrounding';
import { OutfitImageService } from '../services/outfitImageService';

interface OutfitImageGalleryProps {
  records: OutfitImageRecord[];
  onDelete: (record: OutfitImageRecord) => Promise<void>;
  onRefresh: () => Promise<void>;
  onRetry?: (record: OutfitImageRecord) => Promise<void>;
  onLoadMore?: () => Promise<void>;
  loading?: boolean;
  loadingMore?: boolean;
  hasMore?: boolean;
  className?: string;
}

type ViewMode = 'grid' | 'list';
type FilterType = 'all' | OutfitImageStatus;

/**
 * 穿搭图片画廊组件
 * 展示穿搭图片生成记录和结果
 */
export const OutfitImageGallery: React.FC<OutfitImageGalleryProps> = ({
  records,
  onDelete,
  onRefresh,
  onRetry,
  onLoadMore,
  loading = false,
  loadingMore = false,
  hasMore = false,
  className = ''
}) => {
  const [viewMode, setViewMode] = useState<ViewMode>('grid');
  const [filter, setFilter] = useState<FilterType>('all');
  const [searchQuery, setSearchQuery] = useState('');

  // 渲染生成方式标识（单选按钮样式）
  const renderGenerationType = (record: OutfitImageRecord) => {
    if (record.generation_type === 'local_comfyui') {
      return (
        <div className="inline-flex items-center px-3 py-1.5 rounded-full text-xs font-medium bg-blue-50 border border-blue-200">
          <div className="w-3 h-3 rounded-full border-2 border-blue-500 bg-blue-500 mr-2 flex items-center justify-center">
            <div className="w-1.5 h-1.5 rounded-full bg-white"></div>
          </div>
          <span className="text-blue-700 font-semibold">本地ComfyUI</span>
        </div>
      );
    } else if (record.generation_type === 'modal_cloud') {
      return (
        <div className="inline-flex items-center px-3 py-1.5 rounded-full text-xs font-medium bg-purple-50 border border-purple-200">
          <div className="w-3 h-3 rounded-full border-2 border-purple-500 bg-purple-500 mr-2 flex items-center justify-center">
            <div className="w-1.5 h-1.5 rounded-full bg-white"></div>
          </div>
          <span className="text-purple-700 font-semibold">云端Modal</span>
        </div>
      );
    }
    return null;
  };

  // 图片预览模态框状态
  const [previewModal, setPreviewModal] = useState<{
    isOpen: boolean;
    source: GroundingSource | null;
    images: string[];
    currentIndex: number;
  }>({
    isOpen: false,
    source: null,
    images: [],
    currentIndex: 0
  });

  // 删除确认对话框状态
  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    record: OutfitImageRecord | null;
    deleting: boolean;
  }>({
    show: false,
    record: null,
    deleting: false
  });

  // 重试状态管理
  const [retryingRecords, setRetryingRecords] = useState<Set<string>>(new Set());

  // 过滤记录
  const filteredRecords = records.filter(record => {
    const matchesFilter = filter === 'all' || record.status === filter;
    const matchesSearch = searchQuery === '' || 
      (record.generation_prompt && record.generation_prompt.toLowerCase().includes(searchQuery.toLowerCase()));
    
    return matchesFilter && matchesSearch;
  });

  // 处理删除确认
  const handleDeleteClick = useCallback((record: OutfitImageRecord) => {
    setDeleteConfirm({
      show: true,
      record,
      deleting: false
    });
  }, []);

  // 确认删除
  const confirmDelete = useCallback(async () => {
    if (!deleteConfirm.record) return;

    try {
      setDeleteConfirm(prev => ({ ...prev, deleting: true }));
      await onDelete(deleteConfirm.record);
      setDeleteConfirm({ show: false, record: null, deleting: false });
    } catch (error) {
      console.error('删除失败:', error);
      setDeleteConfirm(prev => ({ ...prev, deleting: false }));
    }
  }, [deleteConfirm.record, onDelete]);

  // 取消删除
  const cancelDelete = useCallback(() => {
    setDeleteConfirm({ show: false, record: null, deleting: false });
  }, []);

  // 处理重试
  const handleRetry = useCallback(async (record: OutfitImageRecord) => {
    if (retryingRecords.has(record.id)) return;

    try {
      setRetryingRecords(prev => new Set(prev).add(record.id));

      if (onRetry) {
        // 使用父组件提供的重试方法
        await onRetry(record);
      } else {
        // 使用默认的重试方法
        await OutfitImageService.retryOutfitImageGeneration(record.id);
        await onRefresh();
      }
    } catch (error) {
      console.error('重试失败:', error);
    } finally {
      setRetryingRecords(prev => {
        const newSet = new Set(prev);
        newSet.delete(record.id);
        return newSet;
      });
    }
  }, [retryingRecords, onRetry, onRefresh]);

  // 打开图片预览
  const openImagePreview = useCallback((imageUrl: string, title: string, allImages: string[] = [], currentIndex: number = 0) => {
    console.log('🖼️ 打开图片预览:', { imageUrl, title, allImages, currentIndex });
    const source: GroundingSource = {
      uri: imageUrl,
      title: title,
      content: { description: '穿搭生成图片' }
    };
    setPreviewModal({
      isOpen: true,
      source,
      images: allImages,
      currentIndex
    });
    console.log('🖼️ 预览模态框状态已更新:', { isOpen: true, source, images: allImages, currentIndex });
  }, []);

  // 关闭图片预览
  const closeImagePreview = useCallback(() => {
    setPreviewModal({
      isOpen: false,
      source: null,
      images: [],
      currentIndex: 0
    });
  }, []);

  const getStatusIcon = (status: OutfitImageStatus) => {
    switch (status) {
      case OutfitImageStatus.Pending:
        return <Clock className="w-4 h-4 text-gray-500" />;
      case OutfitImageStatus.Processing:
        return <Loader className="w-4 h-4 text-blue-500 animate-spin" />;
      case OutfitImageStatus.Completed:
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case OutfitImageStatus.Failed:
        return <XCircle className="w-4 h-4 text-red-500" />;
      default:
        return <Clock className="w-4 h-4 text-gray-500" />;
    }
  };

  const getStatusLabel = (status: OutfitImageStatus) => {
    switch (status) {
      case OutfitImageStatus.Pending:
        return '等待中';
      case OutfitImageStatus.Processing:
        return '生成中';
      case OutfitImageStatus.Completed:
        return '已完成';
      case OutfitImageStatus.Failed:
        return '失败';
      default:
        return '未知';
    }
  };

  const getStatusColor = (status: OutfitImageStatus) => {
    switch (status) {
      case OutfitImageStatus.Pending:
        return 'bg-gray-100 text-gray-800';
      case OutfitImageStatus.Processing:
        return 'bg-blue-100 text-blue-800';
      case OutfitImageStatus.Completed:
        return 'bg-green-100 text-green-800';
      case OutfitImageStatus.Failed:
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const formatDuration = (ms: number): string => {
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    return `${(ms / 60000).toFixed(1)}min`;
  };

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

  if (loading) {
    return (
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 animate-pulse">
        <div className="flex items-center mb-6">
          <div className="w-2 h-8 bg-gray-200 rounded-full mr-4"></div>
          <div className="h-6 bg-gray-200 rounded w-32"></div>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {[...Array(6)].map((_, index) => (
            <div key={index} className="p-4 bg-gray-50 rounded-xl">
              <div className="h-32 bg-gray-200 rounded-lg mb-3"></div>
              <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
              <div className="h-3 bg-gray-200 rounded w-1/2"></div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className={`space-y-6 ${className}`}>
      {/* 头部工具栏 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <h2 className="text-xl font-bold text-gray-900 flex items-center">
            <Sparkles className="w-6 h-6 text-purple-500 mr-2" />
            穿搭图片生成记录
          </h2>
          <span className="text-sm text-gray-500">
            共 {records.length} 条记录
            {filteredRecords.length !== records.length && ` (显示 ${filteredRecords.length} 条)`}
          </span>
        </div>

        <div className="flex items-center space-x-2">
          {/* 搜索框 */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="搜索提示词..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            />
          </div>

          {/* 状态过滤器 */}
          <select
            value={filter}
            onChange={(e) => setFilter(e.target.value as FilterType)}
            className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          >
            <option value="all">全部状态</option>
            <option value={OutfitImageStatus.Pending}>等待中</option>
            <option value={OutfitImageStatus.Processing}>生成中</option>
            <option value={OutfitImageStatus.Completed}>已完成</option>
            <option value={OutfitImageStatus.Failed}>失败</option>
          </select>

          {/* 视图模式切换 */}
          <div className="flex border border-gray-300 rounded-lg overflow-hidden">
            <button
              onClick={() => setViewMode('grid')}
              className={`p-2 ${viewMode === 'grid' ? 'bg-purple-500 text-white' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
              title="网格视图"
            >
              <Grid3X3 className="w-4 h-4" />
            </button>
            <button
              onClick={() => setViewMode('list')}
              className={`p-2 ${viewMode === 'list' ? 'bg-purple-500 text-white' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
              title="列表视图"
            >
              <List className="w-4 h-4" />
            </button>
          </div>

          {/* 刷新按钮 */}
          <button
            onClick={onRefresh}
            className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
            title="刷新"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
          </button>
        </div>
      </div>

      {/* 记录展示 */}
      {filteredRecords.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-xl">
          <div className="text-6xl mb-4 opacity-50">🎨</div>
          <p className="text-lg font-medium text-gray-600 mb-2">
            {records.length === 0 ? '暂无生成记录' : '没有找到匹配的记录'}
          </p>
          <p className="text-sm text-gray-500">
            {records.length === 0 ? '开始生成您的第一个穿搭图片' : '尝试调整搜索条件或过滤器'}
          </p>
        </div>
      ) : viewMode === 'grid' ? (
        /* 网格视图 */
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredRecords.map((record) => (
            <div
              key={record.id}
              className="bg-white rounded-xl border border-gray-200 overflow-hidden hover:shadow-lg transition-all duration-200"
            >
              {/* 记录头部 */}
              <div className="p-4 border-b border-gray-100">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center space-x-2">
                    <span className={`inline-flex items-center px-2 py-1 text-xs rounded-full ${getStatusColor(record.status)}`}>
                      {getStatusIcon(record.status)}
                      <span className="ml-1">{getStatusLabel(record.status)}</span>
                    </span>
                    {renderGenerationType(record)}
                  </div>
                  <div className="flex items-center space-x-2">
                    {record.status === OutfitImageStatus.Failed && (
                      <button
                        onClick={() => handleRetry(record)}
                        disabled={retryingRecords.has(record.id)}
                        className="p-1 text-blue-600 hover:bg-blue-50 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        title="重试生成"
                      >
                        {retryingRecords.has(record.id) ? (
                          <Loader className="w-4 h-4 animate-spin" />
                        ) : (
                          <RotateCcw className="w-4 h-4" />
                        )}
                      </button>
                    )}
                    <button
                      onClick={() => handleDeleteClick(record)}
                      className="p-1 text-red-600 hover:bg-red-50 rounded transition-colors"
                      title="删除记录"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
                
                {record.generation_prompt && (
                  <p className="text-sm text-gray-600 line-clamp-2 mb-2">
                    {record.generation_prompt}
                  </p>
                )}
                
                <div className="flex items-center text-xs text-gray-500">
                  <Calendar className="w-3 h-3 mr-1" />
                  {formatDate(record.created_at)}
                </div>
              </div>

              {/* 生成结果 */}
              <div className="p-4">
                {record.status === OutfitImageStatus.Processing && (
                  <div className="text-center py-8">
                    <Loader className="w-8 h-8 text-purple-500 animate-spin mx-auto mb-2" />
                    <p className="text-sm text-gray-600 mb-1">
                      生成进度: {Math.round(record.progress * 100)}%
                    </p>
                    <p className="text-xs text-gray-500">
                      商品图片: {record.product_images.length}
                    </p>
                  </div>
                )}

                {record.status === OutfitImageStatus.Completed && record.outfit_images.length > 0 && (
                  <div className="grid grid-cols-2 gap-2">
                    {record.outfit_images.slice(0, 4).map((image, index) => (
                      <div
                        key={image.id}
                        className="aspect-square rounded-lg overflow-hidden relative group cursor-pointer"
                        onClick={(e) => {
                          console.log('🖱️ 图片容器点击事件触发:', {
                            imageUrl: image.image_url,
                            title: `穿搭图片 ${index + 1}`,
                            event: e
                          });
                          e.preventDefault();
                          e.stopPropagation();
                          const allImages = record.outfit_images.map(img => img.image_url);
                          openImagePreview(image.image_url, `穿搭图片 ${index + 1}`, allImages, index);
                        }}
                      >
                        <img
                          src={getImageSrc(image.image_url)}
                          alt={`穿搭图片 ${index + 1}`}
                          className="w-full h-full object-cover hover:scale-105 transition-transform duration-200"
                        />
                        {/* 预览按钮覆盖层 */}
                        <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-all duration-200 flex items-center justify-center pointer-events-none">
                          <Eye className="w-6 h-6 text-white opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
                        </div>
                      </div>
                    ))}
                    {record.outfit_images.length > 4 && (
                      <div className="aspect-square rounded-lg bg-gray-100 flex items-center justify-center">
                        <span className="text-sm text-gray-600">
                          +{record.outfit_images.length - 4}
                        </span>
                      </div>
                    )}
                  </div>
                )}

                {record.status === OutfitImageStatus.Failed && (
                  <div className="text-center py-8">
                    <XCircle className="w-8 h-8 text-red-500 mx-auto mb-2" />
                    <p className="text-sm text-red-600 mb-3">
                      {record.error_message || '生成失败'}
                    </p>
                    <button
                      onClick={() => handleRetry(record)}
                      disabled={retryingRecords.has(record.id)}
                      className="inline-flex items-center px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      {retryingRecords.has(record.id) ? (
                        <>
                          <Loader className="w-4 h-4 animate-spin mr-1" />
                          重试中...
                        </>
                      ) : (
                        <>
                          <RotateCcw className="w-4 h-4 mr-1" />
                          重试
                        </>
                      )}
                    </button>
                  </div>
                )}

                {/* 统计信息 */}
                <div className="mt-4 pt-4 border-t border-gray-100">
                  <div className="flex items-center justify-between text-xs text-gray-500 mb-2">
                    <span>商品图片: {record.product_images.length}</span>
                    <span>生成图片: {record.outfit_images.length}</span>
                    {record.duration_ms && (
                      <span>耗时: {formatDuration(record.duration_ms)}</span>
                    )}
                  </div>
                  {record.comfyui_prompt_id && (
                    <div className="text-xs text-gray-500">
                      <span className="font-mono bg-gray-100 px-2 py-1 rounded">
                        任务ID: {record.comfyui_prompt_id}
                      </span>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        /* 列表视图 */
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <div className="divide-y divide-gray-200">
            {filteredRecords.map((record) => (
              <div key={record.id} className="p-4 hover:bg-gray-50 transition-colors">
                <div className="flex items-center justify-between">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-3 mb-2">
                      <span className={`inline-flex items-center px-2 py-1 text-xs rounded-full ${getStatusColor(record.status)}`}>
                        {getStatusIcon(record.status)}
                        <span className="ml-1">{getStatusLabel(record.status)}</span>
                      </span>
                      {renderGenerationType(record)}
                      <span className="text-sm text-gray-500">
                        {formatDate(record.created_at)}
                      </span>
                      {record.duration_ms && (
                        <span className="text-sm text-gray-500">
                          耗时: {formatDuration(record.duration_ms)}
                        </span>
                      )}
                    </div>
                    
                    {record.generation_prompt && (
                      <p className="text-sm text-gray-600 mb-2">
                        {record.generation_prompt}
                      </p>
                    )}
                    
                    <div className="flex items-center space-x-4 text-xs text-gray-500">
                      <span>商品图片: {record.product_images.length}</span>
                      <span>生成图片: {record.outfit_images.length}</span>
                      {record.status === OutfitImageStatus.Processing && (
                        <span>进度: {Math.round(record.progress * 100)}%</span>
                      )}
                      {record.comfyui_prompt_id && (
                        <span className="font-mono bg-gray-100 px-2 py-1 rounded">
                          任务ID: {record.comfyui_prompt_id}
                        </span>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center space-x-2">
                    {record.status === OutfitImageStatus.Completed && record.outfit_images.length > 0 && (
                      <div className="flex -space-x-2">
                        {record.outfit_images.slice(0, 3).map((image, index) => (
                          <div
                            key={image.id}
                            className="w-10 h-10 rounded-lg overflow-hidden border-2 border-white cursor-pointer hover:scale-110 transition-transform duration-200"
                            onClick={(e) => {
                              console.log('🖱️ 列表图片点击事件触发:', {
                                imageUrl: image.image_url,
                                title: `穿搭图片 ${index + 1}`,
                                event: e
                              });
                              e.preventDefault();
                              e.stopPropagation();
                              const allImages = record.outfit_images.map(img => img.image_url);
                              openImagePreview(image.image_url, `穿搭图片 ${index + 1}`, allImages, index);
                            }}
                          >
                            <img
                              src={getImageSrc(image.image_url)}
                              alt={`穿搭图片 ${index + 1}`}
                              className="w-full h-full object-cover"
                            />
                          </div>
                        ))}
                      </div>
                    )}

                    {record.status === OutfitImageStatus.Failed && (
                      <button
                        onClick={() => handleRetry(record)}
                        disabled={retryingRecords.has(record.id)}
                        className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        title="重试生成"
                      >
                        {retryingRecords.has(record.id) ? (
                          <Loader className="w-4 h-4 animate-spin" />
                        ) : (
                          <RotateCcw className="w-4 h-4" />
                        )}
                      </button>
                    )}

                    <button
                      onClick={() => handleDeleteClick(record)}
                      className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                      title="删除记录"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 加载更多按钮 */}
      {hasMore && (
        <div className="mt-8 text-center">
          <button
            onClick={onLoadMore}
            disabled={loadingMore}
            className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {loadingMore ? (
              <>
                <Loader className="w-4 h-4 animate-spin inline mr-2" />
                加载中...
              </>
            ) : (
              `加载更多 (${records.length} 条记录)`
            )}
          </button>
        </div>
      )}

      {/* 删除确认对话框 */}
      <DeleteConfirmDialog
        isOpen={deleteConfirm.show}
        title="删除生成记录"
        message={`确定要删除这条穿搭图片生成记录吗？此操作无法撤销。`}
        onConfirm={confirmDelete}
        onCancel={cancelDelete}
        deleting={deleteConfirm.deleting}
      />

      {/* 图片预览模态框 */}
      <ImagePreviewModal
        isOpen={previewModal.isOpen}
        source={previewModal.source}
        onClose={closeImagePreview}
        images={previewModal.images}
        currentIndex={previewModal.currentIndex}
        onNavigate={(newIndex) => {
          if (previewModal.images[newIndex]) {
            const newImageUrl = previewModal.images[newIndex];
            const newSource: GroundingSource = {
              uri: newImageUrl,
              title: `穿搭图片 ${newIndex + 1}`,
              content: { description: '穿搭生成图片' }
            };
            setPreviewModal({
              ...previewModal,
              source: newSource,
              currentIndex: newIndex
            });
          }
        }}
      />
    </div>
  );
};

export default OutfitImageGallery;
