import React, { useState, useCallback, useEffect } from 'react';
import {
  Upload,
  Settings,
  Play,
  RotateCcw,
  FolderOpen,
  Wand2,
  CheckCircle,
  Clock,
  Loader,
  XCircle,
  Ban,
  Eye,
  Save
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { open } from '@tauri-apps/plugin-dialog';
import {
  ImageEditingTask,
  BatchImageEditingTask,
  ImageEditingParams,
  ImageEditingConfig,
  ImageEditingTaskStatus,
  DEFAULT_IMAGE_EDITING_PARAMS,
  DEFAULT_IMAGE_EDITING_CONFIG,
  TASK_STATUS_CONFIG,
  IMAGE_FILE_CONFIG,
} from '../../types/imageEditing';

/**
 * 图像编辑工具页面
 * 支持单张图片编辑和批量处理功能
 */
const ImageEditingTool: React.FC = () => {
  // 状态管理
  const [activeTab, setActiveTab] = useState<'single' | 'batch'>('single');
  const [config, setConfig] = useState<ImageEditingConfig>(DEFAULT_IMAGE_EDITING_CONFIG);
  const [params, setParams] = useState<ImageEditingParams>(DEFAULT_IMAGE_EDITING_PARAMS);
  
  // 单张图片编辑状态
  const [selectedImage, setSelectedImage] = useState<string>('');
  const [outputPath, setOutputPath] = useState<string>('');
  const [prompt, setPrompt] = useState<string>('去掉模特手上的物品，让模特双手自然放在身体两侧，手里不要拿或者握着物品');
  const [isProcessing, setIsProcessing] = useState<boolean>(false);
  const [result, setResult] = useState<string>('');
  
  // 批量处理状态
  const [inputFolder, setInputFolder] = useState<string>('');
  const [outputFolder, setOutputFolder] = useState<string>('');
  const [batchPrompt, setBatchPrompt] = useState<string>('去掉模特手上的物品，让模特双手自然放在身体两侧，手里不要拿或者握着物品');
  const [batchTask, setBatchTask] = useState<BatchImageEditingTask | null>(null);
  
  // 任务管理状态
  const [tasks, setTasks] = useState<ImageEditingTask[]>([]);
  const [batchTasks, setBatchTasks] = useState<BatchImageEditingTask[]>([]);
  const [showTasks, setShowTasks] = useState<boolean>(false);

  // 配置状态
  const [showConfig, setShowConfig] = useState<boolean>(false);
  const [apiKeyInput, setApiKeyInput] = useState<string>('');

  // 注意：现在使用事件驱动更新，不再需要定时刷新状态

  // 初始化
  useEffect(() => {
    loadTasks();

    // 设置Tauri事件监听
    const setupEventListeners = async () => {
      try {
        // 监听批量任务更新事件
        const unlistenUpdate = await listen<BatchImageEditingTask>('batch-task-updated', (event) => {
          console.log('收到任务更新事件:', event.payload);
          setBatchTasks(prev => {
            const updated = [...prev];
            const index = updated.findIndex(task => task.id === event.payload.id);
            if (index >= 0) {
              updated[index] = event.payload;
            } else {
              updated.push(event.payload);
            }
            return updated;
          });
        });

        // 监听批量任务完成事件
        const unlistenComplete = await listen<BatchImageEditingTask>('batch-task-completed', (event) => {
          console.log('收到任务完成事件:', event.payload);
          setBatchTasks(prev => {
            const updated = [...prev];
            const index = updated.findIndex(task => task.id === event.payload.id);
            if (index >= 0) {
              updated[index] = event.payload;
            }
            return updated;
          });
        });

        // 监听批量任务失败事件
        const unlistenFailed = await listen<BatchImageEditingTask>('batch-task-failed', (event) => {
          console.log('收到任务失败事件:', event.payload);
          setBatchTasks(prev => {
            const updated = [...prev];
            const index = updated.findIndex(task => task.id === event.payload.id);
            if (index >= 0) {
              updated[index] = event.payload;
            }
            return updated;
          });
        });

        // 返回清理函数
        return () => {
          unlistenUpdate();
          unlistenComplete();
          unlistenFailed();
        };
      } catch (error) {
        console.error('设置事件监听失败:', error);
      }
    };

    setupEventListeners();
  }, []);

  // 加载任务列表
  const loadTasks = useCallback(async () => {
    try {
      const [allTasks, allBatchTasks] = await Promise.all([
        invoke<ImageEditingTask[]>('get_all_image_editing_tasks'),
        invoke<BatchImageEditingTask[]>('get_all_batch_editing_tasks'),
      ]);
      setTasks(allTasks);
      setBatchTasks(allBatchTasks);
    } catch (error) {
      console.error('加载任务失败:', error);
    }
  }, []);

  // 注意：现在使用事件驱动的实时更新，不再需要定时刷新和状态检查

  // 设置API密钥
  const handleSetApiKey = useCallback(async () => {
    if (!apiKeyInput.trim()) {
      alert('请输入API密钥');
      return;
    }

    try {
      await invoke('set_image_editing_api_key', { apiKey: apiKeyInput });
      setConfig(prev => ({ ...prev, api_key: apiKeyInput }));
      alert('API密钥设置成功');
      setShowConfig(false);
    } catch (error) {
      console.error('设置API密钥失败:', error);
      alert(`设置API密钥失败: ${error}`);
    }
  }, [apiKeyInput]);

  // 选择图片文件
  const handleSelectImage = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [{
          name: '图片文件',
          extensions: IMAGE_FILE_CONFIG.allowedExtensions,
        }],
      });

      if (selected && typeof selected === 'string') {
        setSelectedImage(selected);
        // 自动生成输出路径
        const pathParts = selected.split('.');
        const extension = pathParts.pop();
        const basePath = pathParts.join('.');
        setOutputPath(`${basePath}_edited.${extension}`);
      }
    } catch (error) {
      console.error('选择图片失败:', error);
      alert(`选择图片失败: ${error}`);
    }
  }, []);

  // 选择输出路径
  const handleSelectOutputPath = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [{
          name: '图片文件',
          extensions: IMAGE_FILE_CONFIG.allowedExtensions,
        }],
      });

      if (selected && typeof selected === 'string') {
        setOutputPath(selected);
      }
    } catch (error) {
      console.error('选择输出路径失败:', error);
      alert(`选择输出路径失败: ${error}`);
    }
  }, []);

  // 选择输入文件夹
  const handleSelectInputFolder = useCallback(async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
      });

      if (selected && typeof selected === 'string') {
        setInputFolder(selected);
      }
    } catch (error) {
      console.error('选择输入文件夹失败:', error);
      alert(`选择输入文件夹失败: ${error}`);
    }
  }, []);

  // 选择输出文件夹
  const handleSelectOutputFolder = useCallback(async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
      });

      if (selected && typeof selected === 'string') {
        setOutputFolder(selected);
      }
    } catch (error) {
      console.error('选择输出文件夹失败:', error);
      alert(`选择输出文件夹失败: ${error}`);
    }
  }, []);

  // 编辑单张图片
  const handleEditSingleImage = useCallback(async () => {
    if (!selectedImage || !outputPath || !prompt.trim()) {
      alert('请选择图片、输出路径并输入提示词');
      return;
    }

    if (!config.api_key) {
      alert('请先设置API密钥');
      setShowConfig(true);
      return;
    }

    setIsProcessing(true);
    setResult('');

    try {
      await invoke<string>('edit_single_image', {
        inputPath: selectedImage,
        outputPath: outputPath,
        prompt: prompt,
        params: params,
      });

      setResult(`图像编辑完成，输出路径: ${outputPath}`);
      alert('图片编辑完成！');
      loadTasks(); // 刷新任务列表
    } catch (error) {
      console.error('图片编辑失败:', error);
      alert(`图片编辑失败: ${error}`);
    } finally {
      setIsProcessing(false);
    }
  }, [selectedImage, outputPath, prompt, params, config.api_key, loadTasks]);

  // 批量编辑图片
  const handleBatchEdit = useCallback(async () => {
    if (!inputFolder || !outputFolder || !batchPrompt.trim()) {
      alert('请选择输入文件夹、输出文件夹并输入提示词');
      return;
    }

    if (!config.api_key) {
      alert('请先设置API密钥');
      setShowConfig(true);
      return;
    }

    setIsProcessing(true);
    setBatchTask(null);

    try {
      const taskId = await invoke<string>('edit_batch_images', {
        inputFolder: inputFolder,
        outputFolder: outputFolder,
        prompt: batchPrompt,
        params: params,
      });

      console.log('批量处理任务已创建，任务ID:', taskId);
      setIsProcessing(false);
      alert('批量处理任务已启动！');

      // 立即刷新任务列表以显示新创建的任务
      loadTasks();

    } catch (error) {
      console.error('批量编辑失败:', error);
      alert(`批量编辑失败: ${error}`);
      setIsProcessing(false);
    }
  }, [inputFolder, outputFolder, batchPrompt, params, config.api_key, loadTasks]);



  // 获取状态图标
  const getStatusIcon = (status: ImageEditingTaskStatus) => {
    const config = TASK_STATUS_CONFIG[status];
    switch (config.icon) {
      case 'Clock': return <Clock className="w-4 h-4" />;
      case 'Loader': return <Loader className="w-4 h-4 animate-spin" />;
      case 'CheckCircle': return <CheckCircle className="w-4 h-4" />;
      case 'XCircle': return <XCircle className="w-4 h-4" />;
      case 'Ban': return <Ban className="w-4 h-4" />;
      default: return <Clock className="w-4 h-4" />;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-50">
      <div className="container mx-auto px-4 py-8 max-w-7xl">
        {/* 页面标题 */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <div className="p-3 bg-gradient-to-r from-purple-500 to-pink-500 rounded-xl">
              <Wand2 className="w-8 h-8 text-white" />
            </div>
            <div>
              <h1 className="text-3xl font-bold text-gray-900">图像编辑工具</h1>
              <p className="text-gray-600 mt-1">基于火山云SeedEdit 3.0 API的智能图像编辑工具</p>
            </div>
          </div>

          {/* 工具栏 */}
          <div className="flex items-center gap-4">
            <div className="flex bg-white rounded-lg border border-gray-200 p-1">
              <button
                onClick={() => setActiveTab('single')}
                className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                  activeTab === 'single'
                    ? 'bg-blue-500 text-white'
                    : 'text-gray-600 hover:text-gray-900'
                }`}
              >
                单张编辑
              </button>
              <button
                onClick={() => setActiveTab('batch')}
                className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                  activeTab === 'batch'
                    ? 'bg-blue-500 text-white'
                    : 'text-gray-600 hover:text-gray-900'
                }`}
              >
                批量处理
              </button>
            </div>

            <button
              onClick={() => setShowConfig(true)}
              className="flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
            >
              <Settings className="w-4 h-4" />
              配置
            </button>

            <button
              onClick={() => setShowTasks(true)}
              className="flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
            >
              <Eye className="w-4 h-4" />
              任务管理
            </button>
          </div>
        </div>

        {/* 主要内容区域 */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 左侧：编辑界面 */}
          <div className="lg:col-span-2">
            {activeTab === 'single' ? (
              // 单张图片编辑界面
              <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h2 className="text-xl font-semibold text-gray-900 mb-6">单张图片编辑</h2>
                
                {/* 图片选择 */}
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    选择图片
                  </label>
                  <div className="flex gap-4">
                    <button
                      onClick={handleSelectImage}
                      className="flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      <Upload className="w-4 h-4" />
                      选择图片
                    </button>
                    {selectedImage && (
                      <div className="flex-1 px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm text-gray-600 truncate">
                        {selectedImage}
                      </div>
                    )}
                  </div>
                </div>

                {/* 输出路径 */}
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    输出路径
                  </label>
                  <div className="flex gap-4">
                    <button
                      onClick={handleSelectOutputPath}
                      className="flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      <Save className="w-4 h-4" />
                      选择路径
                    </button>
                    {outputPath && (
                      <div className="flex-1 px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm text-gray-600 truncate">
                        {outputPath}
                      </div>
                    )}
                  </div>
                </div>

                {/* 提示词输入 */}
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    编辑提示词
                  </label>
                  <textarea
                    value={prompt}
                    onChange={(e) => setPrompt(e.target.value)}
                    placeholder="请输入图像编辑的提示词，例如：改成爱心形状的泡泡"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                    rows={3}
                  />
                </div>

                {/* 操作按钮 */}
                <div className="flex gap-4">
                  <button
                    onClick={handleEditSingleImage}
                    disabled={isProcessing || !selectedImage || !outputPath || !prompt.trim()}
                    className="flex items-center gap-2 px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    {isProcessing ? (
                      <Loader className="w-4 h-4 animate-spin" />
                    ) : (
                      <Play className="w-4 h-4" />
                    )}
                    {isProcessing ? '处理中...' : '开始编辑'}
                  </button>

                  <button
                    onClick={() => {
                      setSelectedImage('');
                      setOutputPath('');
                      setPrompt('');
                      setResult('');
                    }}
                    className="flex items-center gap-2 px-4 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    <RotateCcw className="w-4 h-4" />
                    重置
                  </button>
                </div>

                {/* 结果显示 */}
                {result && (
                  <div className="mt-6 p-4 bg-green-50 border border-green-200 rounded-lg">
                    <div className="flex items-center gap-2 text-green-800">
                      <CheckCircle className="w-4 h-4" />
                      <span className="font-medium">编辑完成</span>
                    </div>
                    <p className="text-green-700 mt-1 text-sm">{result}</p>
                  </div>
                )}
              </div>
            ) : (
              // 批量处理界面
              <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h2 className="text-xl font-semibold text-gray-900 mb-6">批量图片处理</h2>
                
                {/* 文件夹选择 */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      输入文件夹
                    </label>
                    <button
                      onClick={handleSelectInputFolder}
                      className="w-full flex items-center gap-2 px-4 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      <FolderOpen className="w-4 h-4" />
                      选择输入文件夹
                    </button>
                    {inputFolder && (
                      <div className="mt-2 px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm text-gray-600 truncate">
                        {inputFolder}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      输出文件夹
                    </label>
                    <button
                      onClick={handleSelectOutputFolder}
                      className="w-full flex items-center gap-2 px-4 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      <FolderOpen className="w-4 h-4" />
                      选择输出文件夹
                    </button>
                    {outputFolder && (
                      <div className="mt-2 px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm text-gray-600 truncate">
                        {outputFolder}
                      </div>
                    )}
                  </div>
                </div>

                {/* 提示词输入 */}
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    批量编辑提示词
                  </label>
                  <textarea
                    value={batchPrompt}
                    onChange={(e) => setBatchPrompt(e.target.value)}
                    placeholder="请输入批量编辑的提示词，将应用到所有图片"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                    rows={3}
                  />
                </div>

                {/* 操作按钮 */}
                <div className="flex gap-4 mb-6">
                  <button
                    onClick={handleBatchEdit}
                    disabled={isProcessing || !inputFolder || !outputFolder || !batchPrompt.trim()}
                    className="flex items-center gap-2 px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    {isProcessing ? (
                      <Loader className="w-4 h-4 animate-spin" />
                    ) : (
                      <Play className="w-4 h-4" />
                    )}
                    {isProcessing ? '处理中...' : '开始批量处理'}
                  </button>

                  <button
                    onClick={() => {
                      setInputFolder('');
                      setOutputFolder('');
                      setBatchPrompt('');
                      setBatchTask(null);
                    }}
                    className="flex items-center gap-2 px-4 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    <RotateCcw className="w-4 h-4" />
                    重置
                  </button>
                </div>

                {/* 批量处理进度 */}
                {batchTask && (
                  <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                    <div className="flex items-center justify-between mb-2">
                      <div className="flex items-center gap-2">
                        {getStatusIcon(batchTask.status)}
                        <span className="font-medium text-blue-900">
                          {TASK_STATUS_CONFIG[batchTask.status].label}
                        </span>
                      </div>
                      <span className="text-sm text-blue-700">
                        {batchTask.processed_images} / {batchTask.total_images}
                      </span>
                    </div>
                    
                    <div className="w-full bg-blue-200 rounded-full h-2 mb-2">
                      <div
                        className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                        style={{ width: `${batchTask.progress * 100}%` }}
                      />
                    </div>
                    
                    <div className="text-sm text-blue-700">
                      成功: {batchTask.successful_images} | 失败: {batchTask.failed_images}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* 右侧：参数配置和任务列表 */}
          <div className="space-y-6">
            {/* 任务列表 */}
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">最近任务</h3>

              <div className="space-y-3 max-h-64 overflow-y-auto">
                {/* 显示最近的单个任务 */}
                {tasks.slice(0, 3).map((task) => (
                  <div key={task.id} className="p-3 border border-gray-200 rounded-lg">
                    <div className="flex items-center gap-2 mb-1">
                      {getStatusIcon(task.status)}
                      <span className="text-sm font-medium text-gray-900">
                        {TASK_STATUS_CONFIG[task.status].label}
                      </span>
                    </div>
                    <div className="text-xs text-gray-600 truncate">
                      {task.prompt.substring(0, 40)}...
                    </div>
                    <div className="text-xs text-gray-500 mt-1">
                      {new Date(task.created_at).toLocaleString()}
                    </div>
                    {task.progress > 0 && (
                      <div className="mt-2 w-full bg-gray-200 rounded-full h-1">
                        <div
                          className="bg-blue-500 h-1 rounded-full transition-all duration-300"
                          style={{ width: `${task.progress * 100}%` }}
                        />
                      </div>
                    )}
                  </div>
                ))}

                {/* 显示最近的批量任务 */}
                {batchTasks.slice(0, 2).map((task) => (
                  <div key={task.id} className="p-3 border border-gray-200 rounded-lg bg-blue-50">
                    <div className="flex items-center gap-2 mb-1">
                      {getStatusIcon(task.status)}
                      <span className="text-sm font-medium text-blue-900">
                        批量 - {TASK_STATUS_CONFIG[task.status].label}
                      </span>
                    </div>
                    <div className="text-xs text-blue-700 truncate">
                      {task.prompt.substring(0, 40)}...
                    </div>
                    <div className="text-xs text-blue-600 mt-1">
                      {task.processed_images} / {task.total_images} 已处理
                    </div>
                    {task.progress > 0 && (
                      <div className="mt-2 w-full bg-blue-200 rounded-full h-1">
                        <div
                          className="bg-blue-500 h-1 rounded-full transition-all duration-300"
                          style={{ width: `${task.progress * 100}%` }}
                        />
                      </div>
                    )}
                  </div>
                ))}

                {tasks.length === 0 && batchTasks.length === 0 && (
                  <div className="text-center py-4 text-gray-500 text-sm">
                    暂无任务
                  </div>
                )}
              </div>

              {(tasks.length > 3 || batchTasks.length > 2) && (
                <button
                  onClick={() => setShowTasks(true)}
                  className="w-full mt-3 px-3 py-2 text-sm text-blue-600 border border-blue-200 rounded-lg hover:bg-blue-50 transition-colors"
                >
                  查看全部任务
                </button>
              )}
            </div>

            {/* 参数配置 */}
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">参数配置</h3>
              
              <div className="space-y-4">
                {/* 引导强度 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    引导强度: {params.guidance_scale}
                  </label>
                  <input
                    type="range"
                    min="1"
                    max="10"
                    step="0.5"
                    value={params.guidance_scale}
                    onChange={(e) => setParams(prev => ({
                      ...prev,
                      guidance_scale: parseFloat(e.target.value)
                    }))}
                    className="w-full"
                  />
                  <div className="flex justify-between text-xs text-gray-500 mt-1">
                    <span>低引导</span>
                    <span>高引导</span>
                  </div>
                </div>

                {/* 随机种子 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    随机种子
                  </label>
                  <input
                    type="number"
                    value={params.seed}
                    onChange={(e) => setParams(prev => ({
                      ...prev,
                      seed: parseInt(e.target.value) || -1
                    }))}
                    placeholder="-1 (随机)"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>

                {/* 水印设置 */}
                <div>
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={params.watermark}
                      onChange={(e) => setParams(prev => ({
                        ...prev,
                        watermark: e.target.checked
                      }))}
                      className="rounded border-gray-300 text-blue-500 focus:ring-blue-500"
                    />
                    <span className="text-sm font-medium text-gray-700">
                      添加AI生成水印
                    </span>
                  </label>
                </div>
              </div>
            </div>

            {/* 将任务管理里的任务列表放到这里 */}
          </div>
        </div>

        {/* 配置模态框 */}
        {showConfig && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-xl shadow-xl p-6 w-full max-w-md mx-4">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">API配置</h3>
              
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    API密钥
                  </label>
                  <input
                    type="password"
                    value={apiKeyInput}
                    onChange={(e) => setApiKeyInput(e.target.value)}
                    placeholder="请输入火山云API密钥"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>

                <div className="text-sm text-gray-600">
                  <p>当前配置:</p>
                  <p>API地址: {config.api_url}</p>
                  <p>模型ID: {config.model_id}</p>
                  <p>API密钥: {config.api_key ? '已设置' : '未设置'}</p>
                </div>
              </div>

              <div className="flex gap-3 mt-6">
                <button
                  onClick={handleSetApiKey}
                  className="flex-1 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                >
                  保存配置
                </button>
                <button
                  onClick={() => setShowConfig(false)}
                  className="flex-1 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 任务管理模态框 */}
        {showTasks && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-xl shadow-xl p-6 w-full max-w-4xl mx-4 max-h-[80vh] overflow-y-auto">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold text-gray-900">任务管理</h3>
                <button
                  onClick={() => setShowTasks(false)}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <XCircle className="w-5 h-5" />
                </button>
              </div>

              {/* 任务列表 */}
              <div className="space-y-4">
                {/* 单个任务 */}
                {tasks.length > 0 && (
                  <div>
                    <h4 className="font-medium text-gray-900 mb-2">单个任务</h4>
                    <div className="space-y-2">
                      {tasks.map((task) => (
                        <div key={task.id} className="p-3 border border-gray-200 rounded-lg">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              {getStatusIcon(task.status)}
                              <span className="text-sm font-medium">
                                {task.prompt.substring(0, 30)}...
                              </span>
                            </div>
                            <span className="text-xs text-gray-500">
                              {new Date(task.created_at).toLocaleString()}
                            </span>
                          </div>
                          <div className="mt-1 text-xs text-gray-600">
                            输入: {task.input_image_path.split('/').pop()}
                          </div>
                          {task.progress > 0 && (
                            <div className="mt-2 w-full bg-gray-200 rounded-full h-1">
                              <div
                                className="bg-blue-500 h-1 rounded-full"
                                style={{ width: `${task.progress * 100}%` }}
                              />
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* 批量任务 */}
                {batchTasks.length > 0 && (
                  <div>
                    <h4 className="font-medium text-gray-900 mb-2">批量任务</h4>
                    <div className="space-y-2">
                      {batchTasks.map((task) => (
                        <div key={task.id} className="p-3 border border-gray-200 rounded-lg">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              {getStatusIcon(task.status)}
                              <span className="text-sm font-medium">
                                {task.prompt.substring(0, 30)}...
                              </span>
                            </div>
                            <span className="text-xs text-gray-500">
                              {new Date(task.created_at).toLocaleString()}
                            </span>
                          </div>
                          <div className="mt-1 text-xs text-gray-600">
                            {task.processed_images} / {task.total_images} 已处理
                            (成功: {task.successful_images}, 失败: {task.failed_images})
                          </div>
                          {task.progress > 0 && (
                            <div className="mt-2 w-full bg-gray-200 rounded-full h-1">
                              <div
                                className="bg-blue-500 h-1 rounded-full"
                                style={{ width: `${task.progress * 100}%` }}
                              />
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {tasks.length === 0 && batchTasks.length === 0 && (
                  <div className="text-center py-8 text-gray-500">
                    暂无任务
                  </div>
                )}
              </div>

              <div className="flex gap-3 mt-6">
                <button
                  onClick={loadTasks}
                  className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                >
                  刷新
                </button>
                <button
                  onClick={async () => {
                    try {
                      await invoke('clear_completed_tasks');
                      loadTasks();
                    } catch (error) {
                      console.error('清理任务失败:', error);
                    }
                  }}
                  className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  清理已完成
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ImageEditingTool;
