import React, { useState, useEffect } from 'react';
import { X, Droplets, Search, Plus, Upload, Trash2, Pause } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';
import { Material } from '../types/material';
import { WatermarkTemplate, WatermarkConfig, WatermarkDetectionConfig, WatermarkRemovalConfig, BatchWatermarkTask, WatermarkDetectionResult, WatermarkProcessingResult, DetectionMethod } from '../types/watermark';
import { CustomSelect } from './CustomSelect';
import { LoadingSpinner } from './LoadingSpinner';
import { DeleteConfirmDialog } from './DeleteConfirmDialog';
import { WatermarkTemplateThumbnail } from './WatermarkTemplateThumbnail';

interface WatermarkToolDialogProps {
  isOpen: boolean;
  onClose: () => void;
  selectedMaterials: Material[];
}

enum WatermarkTab {
  DETECT = 'detect',
  REMOVE = 'remove',
  ADD = 'add'
}

interface BatchTaskProgress {
  taskId: string;
  operation: string;
  totalItems: number;
  processedItems: number;
  failedItems: number;
  progressPercentage: number;
  isRunning: boolean;
  errors: string[];
  detectionResults?: WatermarkDetectionResult[];
  processingResults?: WatermarkProcessingResult[];
}

export const WatermarkToolDialog: React.FC<WatermarkToolDialogProps> = ({
  isOpen,
  onClose,
  selectedMaterials
}) => {
  const [activeTab, setActiveTab] = useState<WatermarkTab>(WatermarkTab.DETECT);
  const [isLoading, setIsLoading] = useState(false);
  const [watermarkTemplates, setWatermarkTemplates] = useState<WatermarkTemplate[]>([]);
  const [selectedTemplate, setSelectedTemplate] = useState<string>('');
  const [batchProgress, setBatchProgress] = useState<BatchTaskProgress | null>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [templateToDelete, setTemplateToDelete] = useState<string>('');
  const [showUploadDialog, setShowUploadDialog] = useState(false);
  const [thumbnailCache, setThumbnailCache] = useState<Map<string, string>>(new Map());
  const [uploadForm, setUploadForm] = useState({
    name: '',
    category: 'Logo' as const,
    watermark_type: 'Image' as const,
    description: '',
    tags: [] as string[],
    filePath: '' as string
  });

  // 检测配置
  const [detectionConfig, setDetectionConfig] = useState<WatermarkDetectionConfig>({
    similarity_threshold: 0.8,
    min_watermark_size: [32, 32],
    max_watermark_size: [512, 512],
    detection_regions: ['Corners', 'Center'],
    frame_sample_rate: 30,
    methods: ['TemplateMatching', 'EdgeDetection'],
    template_ids: []
  });

  // 移除配置
  const [removalConfig, setRemovalConfig] = useState<WatermarkRemovalConfig>({
    method: 'Inpainting',
    quality_level: 'Medium',
    preserve_aspect_ratio: true,
    target_regions: undefined,
    inpainting_model: undefined,
    blur_radius: 5.0,
    crop_margin: 10
  });

  // 添加配置
  const [additionConfig, setAdditionConfig] = useState<WatermarkConfig>({
    watermark_type: 'Image',
    position: 'BottomRight',
    opacity: 0.8,
    scale: 1.0,
    rotation: 0.0,
    animation: undefined,
    blend_mode: 'Normal',
    quality_level: 'Medium'
  });

  useEffect(() => {
    if (isOpen) {
      loadWatermarkTemplates();
    }
  }, [isOpen]);

  const loadWatermarkTemplates = async () => {
    try {
      const templates = await invoke<WatermarkTemplate[]>('get_watermark_templates');
      setWatermarkTemplates(templates);
    } catch (error) {
      console.error('加载水印模板失败:', error);
    }
  };

  const handleDetectWatermarks = async () => {
    setIsLoading(true);
    try {
      const taskId = await invoke<string>('start_batch_watermark_task', {
        operation: 'Detect',
        materialIds: selectedMaterials.map(m => m.id),
        config: detectionConfig
      });

      setBatchProgress({
        taskId,
        operation: 'detect',
        totalItems: selectedMaterials.length,
        processedItems: 0,
        failedItems: 0,
        progressPercentage: 0,
        isRunning: true,
        errors: []
      });

      // 开始轮询任务状态
      pollTaskProgress(taskId);
    } catch (error) {
      console.error('启动水印检测任务失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleRemoveWatermarks = async () => {
    setIsLoading(true);
    try {
      const taskId = await invoke<string>('start_batch_watermark_task', {
        operation: 'Remove',
        materialIds: selectedMaterials.map(m => m.id),
        config: removalConfig
      });

      setBatchProgress({
        taskId,
        operation: 'remove',
        totalItems: selectedMaterials.length,
        processedItems: 0,
        failedItems: 0,
        progressPercentage: 0,
        isRunning: true,
        errors: []
      });

      pollTaskProgress(taskId);
    } catch (error) {
      console.error('启动水印移除任务失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddWatermarks = async () => {
    if (!selectedTemplate) {
      alert('请选择水印模板');
      return;
    }

    setIsLoading(true);
    try {
      const taskId = await invoke<string>('start_batch_watermark_task', {
        operation: 'Add',
        materialIds: selectedMaterials.map(m => m.id),
        config: { ...additionConfig, templateId: selectedTemplate }
      });

      setBatchProgress({
        taskId,
        operation: 'add',
        totalItems: selectedMaterials.length,
        processedItems: 0,
        failedItems: 0,
        progressPercentage: 0,
        isRunning: true,
        errors: []
      });

      pollTaskProgress(taskId);
    } catch (error) {
      console.error('启动水印添加任务失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const pollTaskProgress = async (taskId: string) => {
    const interval = setInterval(async () => {
      try {
        const task = await invoke<BatchWatermarkTask>('get_batch_task_status', { taskId });

        // 更新进度状态
        setBatchProgress({
          taskId: task.task_id,
          operation: task.operation,
          totalItems: task.progress.total_items,
          processedItems: task.progress.processed_items,
          failedItems: task.progress.failed_items,
          progressPercentage: task.progress.progress_percentage,
          isRunning: task.status === 'Running',
          errors: task.progress.errors,
          detectionResults: task.progress.detection_results,
          processingResults: task.progress.processing_results
        });

        // 如果任务完成，停止轮询
        if (task.status === 'Completed' || task.status === 'Failed' || task.status === 'Cancelled') {
          clearInterval(interval);
          console.log(`任务${task.status === 'Completed' ? '完成' : '结束'}:`, task);
        }
      } catch (error) {
        console.error('获取任务状态失败:', error);
        clearInterval(interval);
        setBatchProgress(null);
      }
    }, 1000);

    // 10分钟后停止轮询
    setTimeout(() => clearInterval(interval), 600000);
  };

  const handleCancelTask = async () => {
    if (!batchProgress) return;

    try {
      await invoke('cancel_batch_task', { taskId: batchProgress.taskId });
      setBatchProgress(null);
    } catch (error) {
      console.error('取消任务失败:', error);
    }
  };

  const handleDeleteTemplate = async (templateId: string) => {
    setTemplateToDelete(templateId);
    setShowDeleteConfirm(true);
  };

  const confirmDeleteTemplate = async () => {
    try {
      await invoke('delete_watermark_template', { templateId: templateToDelete });
      await loadWatermarkTemplates();
      setShowDeleteConfirm(false);
      setTemplateToDelete('');
    } catch (error) {
      console.error('删除水印模板失败:', error);
    }
  };

  const handleUploadTemplate = () => {
    setShowUploadDialog(true);
  };

  const handleFileSelect = async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [
          {
            name: '图像文件',
            extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg'],
          },
        ],
      });

      if (selected && typeof selected === 'string') {
        const fileName = selected.split(/[/\\]/).pop() || '';
        const nameWithoutExt = fileName.replace(/\.[^/.]+$/, '');

        setUploadForm(prev => ({
          ...prev,
          filePath: selected,
          name: prev.name || nameWithoutExt // 如果没有名称，使用文件名
        }));
      }
    } catch (error) {
      console.error('文件选择失败:', error);
      alert('文件选择失败');
    }
  };

  const submitUploadTemplate = async () => {
    if (!uploadForm.filePath) {
      alert('请选择文件');
      return;
    }

    if (!uploadForm.name.trim()) {
      alert('请输入模板名称');
      return;
    }

    try {
      await invoke('upload_watermark_template', {
        name: uploadForm.name,
        filePath: uploadForm.filePath,
        category: uploadForm.category,
        watermarkType: uploadForm.watermark_type,
        description: uploadForm.description || null,
        tags: uploadForm.tags
      });

      await loadWatermarkTemplates();
      setShowUploadDialog(false);
      setUploadForm({
        name: '',
        category: 'Logo',
        watermark_type: 'Image',
        description: '',
        tags: [],
        filePath: ''
      });

      alert('模板上传成功！');
    } catch (error) {
      console.error('上传水印模板失败:', error);
      alert('上传失败: ' + error);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center space-x-3">
            <Droplets className="w-6 h-6 text-blue-600" />
            <h2 className="text-xl font-semibold text-gray-900">批量水印处理工具</h2>
            <span className="text-sm text-gray-500">
              已选择 {selectedMaterials.length} 个素材
            </span>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 标签页导航 */}
        <div className="flex border-b border-gray-200">
          {[
            { key: WatermarkTab.DETECT, label: '检测水印', icon: Search },
            { key: WatermarkTab.REMOVE, label: '移除水印', icon: X },
            { key: WatermarkTab.ADD, label: '添加水印', icon: Plus }
          ].map(({ key, label, icon: Icon }) => (
            <button
              key={key}
              onClick={() => setActiveTab(key)}
              className={`flex items-center space-x-2 px-6 py-3 font-medium transition-colors ${
                activeTab === key
                  ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50'
                  : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
              }`}
            >
              <Icon className="w-4 h-4" />
              <span>{label}</span>
            </button>
          ))}
        </div>

        {/* 内容区域 */}
        <div className="p-6 overflow-y-auto max-h-[60vh]">
          {/* 检测水印标签页 */}
          {activeTab === WatermarkTab.DETECT && (
            <div className="space-y-6">
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    相似度阈值
                  </label>
                  <input
                    type="range"
                    min="0.1"
                    max="1.0"
                    step="0.1"
                    value={detectionConfig.similarity_threshold}
                    onChange={(e) => setDetectionConfig({
                      ...detectionConfig,
                      similarity_threshold: parseFloat(e.target.value)
                    })}
                    className="w-full"
                  />
                  <span className="text-sm text-gray-500">
                    {detectionConfig.similarity_threshold}
                  </span>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    帧采样率
                  </label>
                  <input
                    type="number"
                    min="1"
                    max="60"
                    value={detectionConfig.frame_sample_rate}
                    onChange={(e) => setDetectionConfig({
                      ...detectionConfig,
                      frame_sample_rate: parseInt(e.target.value)
                    })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  检测方法
                </label>
                <div className="flex flex-wrap gap-2">
                  {['TemplateMatching', 'EdgeDetection', 'FrequencyAnalysis', 'TransparencyDetection'].map((method) => (
                    <label key={method} className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        checked={detectionConfig.methods.includes(method as DetectionMethod)}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setDetectionConfig({
                              ...detectionConfig,
                              methods: [...detectionConfig.methods, method as DetectionMethod]
                            });
                          } else {
                            setDetectionConfig({
                              ...detectionConfig,
                              methods: detectionConfig.methods.filter(m => m !== method)
                            });
                          }
                        }}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="text-sm text-gray-700">{method}</span>
                    </label>
                  ))}
                </div>
              </div>

              <button
                onClick={handleDetectWatermarks}
                disabled={isLoading || batchProgress?.isRunning}
                className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center space-x-2"
              >
                {isLoading ? (
                  <LoadingSpinner size="small" />
                ) : (
                  <Search className="w-5 h-5" />
                )}
                <span>开始检测水印</span>
              </button>
            </div>
          )}

          {/* 移除水印标签页 */}
          {activeTab === WatermarkTab.REMOVE && (
            <div className="space-y-6">
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    移除方法
                  </label>
                  <CustomSelect
                    value={removalConfig.method}
                    onChange={(value) => setRemovalConfig({
                      ...removalConfig,
                      method: value as any
                    })}
                    options={[
                      { value: 'Inpainting', label: 'AI修复' },
                      { value: 'Blurring', label: '模糊处理' },
                      { value: 'Cropping', label: '裁剪移除' },
                      { value: 'Masking', label: '遮罩覆盖' },
                      { value: 'ContentAware', label: '内容感知填充' },
                      { value: 'Clone', label: '克隆修复' }
                    ]}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    质量级别
                  </label>
                  <CustomSelect
                    value={removalConfig.quality_level}
                    onChange={(value) => setRemovalConfig({
                      ...removalConfig,
                      quality_level: value as any
                    })}
                    options={[
                      { value: 'Low', label: '低质量（快速）' },
                      { value: 'Medium', label: '中等质量' },
                      { value: 'High', label: '高质量' },
                      { value: 'Lossless', label: '无损质量' }
                    ]}
                  />
                </div>
              </div>

              {removalConfig.method === 'Blurring' && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    模糊半径
                  </label>
                  <input
                    type="range"
                    min="1"
                    max="20"
                    step="0.5"
                    value={removalConfig.blur_radius || 5}
                    onChange={(e) => setRemovalConfig({
                      ...removalConfig,
                      blur_radius: parseFloat(e.target.value)
                    })}
                    className="w-full"
                  />
                  <span className="text-sm text-gray-500">
                    {removalConfig.blur_radius}
                  </span>
                </div>
              )}

              <button
                onClick={handleRemoveWatermarks}
                disabled={isLoading || batchProgress?.isRunning}
                className="w-full bg-red-600 text-white py-3 px-4 rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center space-x-2"
              >
                {isLoading ? (
                  <LoadingSpinner size="small" />
                ) : (
                  <X className="w-5 h-5" />
                )}
                <span>开始移除水印</span>
              </button>
            </div>
          )}

          {/* 添加水印标签页 */}
          {activeTab === WatermarkTab.ADD && (
            <div className="space-y-6">
              {/* 水印模板选择 */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <label className="block text-sm font-medium text-gray-700">
                    选择水印模板
                  </label>
                  <button
                    onClick={handleUploadTemplate}
                    className="text-blue-600 hover:text-blue-700 text-sm flex items-center space-x-1"
                  >
                    <Upload className="w-4 h-4" />
                    <span>上传新模板</span>
                  </button>
                </div>

                <div className="grid grid-cols-3 gap-4 max-h-48 overflow-y-auto">
                  {watermarkTemplates.map((template) => (
                    <div
                      key={template.id}
                      className={`relative border-2 rounded-lg p-3 cursor-pointer transition-colors ${
                        selectedTemplate === template.id
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-gray-300'
                      }`}
                      onClick={() => setSelectedTemplate(template.id)}
                    >
                      <div className="mb-2">
                        <WatermarkTemplateThumbnail
                          templateId={template.id}
                          size="large"
                          className="w-full h-16"
                          thumbnailCache={thumbnailCache}
                          setThumbnailCache={setThumbnailCache}
                        />
                      </div>
                      <p className="text-sm font-medium text-gray-900 truncate">
                        {template.name}
                      </p>
                      <p className="text-xs text-gray-500">
                        {template.watermark_type}
                      </p>
                      
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDeleteTemplate(template.id);
                        }}
                        className="absolute top-2 right-2 p-1 bg-red-100 hover:bg-red-200 rounded-full transition-colors"
                      >
                        <Trash2 className="w-3 h-3 text-red-600" />
                      </button>
                    </div>
                  ))}
                </div>
              </div>

              {/* 水印配置 */}
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    位置
                  </label>
                  <CustomSelect
                    value={typeof additionConfig.position === 'string' ? additionConfig.position : 'Custom'}
                    onChange={(value) => setAdditionConfig({
                      ...additionConfig,
                      position: value as any
                    })}
                    options={[
                      { value: 'TopLeft', label: '左上角' },
                      { value: 'TopCenter', label: '顶部居中' },
                      { value: 'TopRight', label: '右上角' },
                      { value: 'MiddleLeft', label: '左侧居中' },
                      { value: 'Center', label: '居中' },
                      { value: 'MiddleRight', label: '右侧居中' },
                      { value: 'BottomLeft', label: '左下角' },
                      { value: 'BottomCenter', label: '底部居中' },
                      { value: 'BottomRight', label: '右下角' }
                    ]}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    透明度
                  </label>
                  <input
                    type="range"
                    min="0.1"
                    max="1.0"
                    step="0.1"
                    value={additionConfig.opacity}
                    onChange={(e) => setAdditionConfig({
                      ...additionConfig,
                      opacity: parseFloat(e.target.value)
                    })}
                    className="w-full"
                  />
                  <span className="text-sm text-gray-500">
                    {Math.round(additionConfig.opacity * 100)}%
                  </span>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    缩放比例
                  </label>
                  <input
                    type="range"
                    min="0.1"
                    max="3.0"
                    step="0.1"
                    value={additionConfig.scale}
                    onChange={(e) => setAdditionConfig({
                      ...additionConfig,
                      scale: parseFloat(e.target.value)
                    })}
                    className="w-full"
                  />
                  <span className="text-sm text-gray-500">
                    {additionConfig.scale}x
                  </span>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    旋转角度
                  </label>
                  <input
                    type="range"
                    min="-180"
                    max="180"
                    step="5"
                    value={additionConfig.rotation}
                    onChange={(e) => setAdditionConfig({
                      ...additionConfig,
                      rotation: parseFloat(e.target.value)
                    })}
                    className="w-full"
                  />
                  <span className="text-sm text-gray-500">
                    {additionConfig.rotation}°
                  </span>
                </div>
              </div>

              <button
                onClick={handleAddWatermarks}
                disabled={isLoading || batchProgress?.isRunning || !selectedTemplate}
                className="w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center space-x-2"
              >
                {isLoading ? (
                  <LoadingSpinner size="small" />
                ) : (
                  <Plus className="w-5 h-5" />
                )}
                <span>开始添加水印</span>
              </button>
            </div>
          )}

          {/* 批量处理进度 */}
          {batchProgress && (
            <div className="mt-6 p-4 bg-gray-50 rounded-lg">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-lg font-medium text-gray-900">
                  批量处理进度 - {batchProgress.operation}
                </h3>
                {batchProgress.isRunning && (
                  <button
                    onClick={handleCancelTask}
                    className="text-red-600 hover:text-red-700 flex items-center space-x-1"
                  >
                    <Pause className="w-4 h-4" />
                    <span>取消</span>
                  </button>
                )}
              </div>

              <div className="w-full bg-gray-200 rounded-full h-2 mb-3">
                <div
                  className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${batchProgress.progressPercentage}%` }}
                />
              </div>

              <div className="flex justify-between text-sm text-gray-600">
                <span>
                  已处理: {batchProgress.processedItems}/{batchProgress.totalItems}
                </span>
                <span>失败: {batchProgress.failedItems}</span>
                <span>{Math.round(batchProgress.progressPercentage)}%</span>
              </div>

              {batchProgress.errors.length > 0 && (
                <div className="mt-3">
                  <p className="text-sm font-medium text-red-600 mb-2">错误信息:</p>
                  <div className="max-h-24 overflow-y-auto">
                    {batchProgress.errors.map((error, index) => (
                      <p key={index} className="text-xs text-red-500">
                        {error}
                      </p>
                    ))}
                  </div>
                </div>
              )}

              {/* 检测结果展示 */}
              {batchProgress.operation === 'Detect' && batchProgress.detectionResults && batchProgress.detectionResults.length > 0 && (
                <div className="mt-4">
                  <p className="text-sm font-medium text-gray-900 mb-3">检测结果:</p>
                  <div className="space-y-3 max-h-48 overflow-y-auto">
                    {batchProgress.detectionResults.map((result, index) => {
                      const materialName = selectedMaterials.find(m => m.id === result.material_id)?.name || result.material_id;
                      return (
                        <div key={index} className="bg-gray-50 rounded-lg p-3">
                          <div className="flex items-center justify-between mb-2">
                            <h4 className="text-sm font-medium text-gray-900 truncate">
                              {materialName}
                            </h4>
                            <div className="flex items-center space-x-2">
                              <span className="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">
                                {result.detection_method}
                              </span>
                              <span className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded">
                                置信度: {(result.confidence_score * 100).toFixed(1)}%
                              </span>
                            </div>
                          </div>

                          {result.detections.length > 0 ? (
                            <div className="space-y-2">
                              <p className="text-xs text-gray-600">
                                发现 {result.detections.length} 个水印区域
                              </p>
                              {result.detections.map((detection, detIndex) => (
                                <div key={detIndex} className="bg-white rounded p-2 text-xs">
                                  <div className="flex justify-between items-center">
                                    <span className="text-gray-600">
                                      位置: ({detection.region.x}, {detection.region.y})
                                      尺寸: {detection.region.width}×{detection.region.height}
                                    </span>
                                    <span className="text-green-600 font-medium">
                                      {(detection.confidence * 100).toFixed(1)}%
                                    </span>
                                  </div>
                                  {detection.watermark_type && (
                                    <p className="text-gray-500 mt-1">
                                      类型: {detection.watermark_type}
                                    </p>
                                  )}
                                  {detection.description && (
                                    <p className="text-gray-500 mt-1">
                                      {detection.description}
                                    </p>
                                  )}
                                </div>
                              ))}
                            </div>
                          ) : (
                            <p className="text-xs text-gray-500">未检测到水印</p>
                          )}

                          <div className="mt-2 text-xs text-gray-400">
                            处理时间: {result.processing_time_ms}ms
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* 处理结果统计 */}
              {batchProgress.processingResults && batchProgress.processingResults.length > 0 && (
                <div className="mt-4">
                  <p className="text-sm font-medium text-gray-900 mb-2">处理统计:</p>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div className="bg-green-50 rounded-lg p-3">
                      <div className="text-green-800 font-medium">
                        成功处理
                      </div>
                      <div className="text-2xl font-bold text-green-600">
                        {batchProgress.processingResults.filter(r => r.success).length}
                      </div>
                    </div>
                    <div className="bg-red-50 rounded-lg p-3">
                      <div className="text-red-800 font-medium">
                        处理失败
                      </div>
                      <div className="text-2xl font-bold text-red-600">
                        {batchProgress.processingResults.filter(r => !r.success).length}
                      </div>
                    </div>
                  </div>

                  {batchProgress.operation === 'Detect' && (
                    <div className="mt-3 grid grid-cols-2 gap-4 text-sm">
                      <div className="bg-blue-50 rounded-lg p-3">
                        <div className="text-blue-800 font-medium">
                          检测到水印
                        </div>
                        <div className="text-2xl font-bold text-blue-600">
                          {batchProgress.detectionResults?.filter(r => r.detections.length > 0).length || 0}
                        </div>
                      </div>
                      <div className="bg-gray-50 rounded-lg p-3">
                        <div className="text-gray-800 font-medium">
                          平均置信度
                        </div>
                        <div className="text-2xl font-bold text-gray-600">
                          {batchProgress.detectionResults && batchProgress.detectionResults.length > 0
                            ? ((batchProgress.detectionResults.reduce((sum, r) => sum + r.confidence_score, 0) / batchProgress.detectionResults.length) * 100).toFixed(1)
                            : '0'}%
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        <div className="flex justify-end space-x-3 p-6 border-t border-gray-200">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
          >
            关闭
          </button>
        </div>
      </div>

      {/* 删除确认对话框 */}
      <DeleteConfirmDialog
        isOpen={showDeleteConfirm}
        onCancel={() => setShowDeleteConfirm(false)}
        onConfirm={confirmDeleteTemplate}
        title="删除水印模板"
        message="确定要删除这个水印模板吗？此操作不可撤销。"
      />

      {/* 上传模板对话框 */}
      {showUploadDialog && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-96 max-h-[80vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">上传水印模板</h3>
              <button
                onClick={() => setShowUploadDialog(false)}
                className="text-gray-400 hover:text-gray-600"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-4">
              {/* 文件选择 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  选择文件
                </label>
                <button
                  onClick={handleFileSelect}
                  className="w-full px-4 py-3 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-400 hover:bg-blue-50 transition-colors flex items-center justify-center space-x-2"
                >
                  <Upload className="w-5 h-5 text-gray-400" />
                  <span className="text-gray-600">点击选择图片文件</span>
                </button>
                {uploadForm.filePath && (
                  <p className="mt-2 text-sm text-gray-600">
                    已选择: {uploadForm.filePath.split(/[/\\]/).pop()}
                  </p>
                )}
              </div>

              {/* 模板名称 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  模板名称
                </label>
                <input
                  type="text"
                  value={uploadForm.name}
                  onChange={(e) => setUploadForm(prev => ({ ...prev, name: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="输入模板名称"
                />
              </div>

              {/* 分类 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  分类
                </label>
                <select
                  value={uploadForm.category}
                  onChange={(e) => setUploadForm(prev => ({ ...prev, category: e.target.value as any }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="Logo">Logo</option>
                  <option value="Copyright">版权</option>
                  <option value="Signature">签名</option>
                  <option value="Decoration">装饰</option>
                  <option value="Custom">自定义</option>
                </select>
              </div>

              {/* 水印类型 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  水印类型
                </label>
                <select
                  value={uploadForm.watermark_type}
                  onChange={(e) => setUploadForm(prev => ({ ...prev, watermark_type: e.target.value as any }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="Image">图片</option>
                  <option value="Vector">矢量</option>
                  <option value="Text">文字</option>
                  <option value="Animated">动画</option>
                </select>
              </div>

              {/* 描述 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  描述 (可选)
                </label>
                <textarea
                  value={uploadForm.description}
                  onChange={(e) => setUploadForm(prev => ({ ...prev, description: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  rows={3}
                  placeholder="输入模板描述"
                />
              </div>
            </div>

            {/* 按钮 */}
            <div className="flex justify-end space-x-3 mt-6">
              <button
                onClick={() => setShowUploadDialog(false)}
                className="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50"
              >
                取消
              </button>
              <button
                onClick={submitUploadTemplate}
                disabled={!uploadForm.filePath || !uploadForm.name.trim()}
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                上传
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
