/**
 * 批量文件夹处理组件
 * 
 * 支持选择文件夹、扫描文件、批量执行任务并保存结果到指定输出文件夹
 */

import React, { useState, useEffect } from 'react';
import { 
  FolderOpen, 
  Play, 
  Square, 
  Settings, 
  FileText, 
  CheckCircle, 
  AlertCircle,
  Clock,
  Folder,
  Image,
  RotateCcw
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';

// 批量任务状态
type BatchTaskStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled';

// 批量处理任务
interface BatchProcessingTask {
  id: string;
  name: string;
  workflow_template_id: number;
  input_folder: string;
  output_folder: string;
  status: BatchTaskStatus;
  total_files: number;
  processed_files: number;
  failed_files: number;
  created_at: string;
  started_at?: string;
  completed_at?: string;
  error_message?: string;
}

// 批量处理进度
interface BatchProcessingProgress {
  task_id: string;
  status: BatchTaskStatus;
  total_files: number;
  processed_files: number;
  failed_files: number;
  current_file?: string;
  progress_percentage: number;
  estimated_remaining_time?: number;
}

// 创建批量任务请求
interface CreateBatchTaskRequest {
  name: string;
  workflow_template_id: number;
  input_folder: string;
  output_folder: string;
  file_extensions: string[];
  recursive: boolean;
}

// 工作流模板
interface WorkflowTemplate {
  id: number;
  name: string;
  base_name: string;
  version: string;
  type: string;
  description?: string;
}

// 组件属性
interface BatchFolderProcessorProps {
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 关闭回调 */
  onClose: () => void;
  /** 任务完成回调 */
  onTaskComplete?: (task: BatchProcessingTask) => void;
}

/**
 * 批量文件夹处理组件
 */
export const BatchFolderProcessor: React.FC<BatchFolderProcessorProps> = ({
  isOpen,
  onClose,
  onTaskComplete
}) => {
  // 状态管理
  const [step, setStep] = useState<'config' | 'preview' | 'processing'>('config');
  const [inputFolder, setInputFolder] = useState('');
  const [outputFolder, setOutputFolder] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState<WorkflowTemplate | null>(null);
  const [fileExtensions, setFileExtensions] = useState<string[]>(['jpg', 'png', 'jpeg']);
  const [recursive, setRecursive] = useState(true);
  const [taskName, setTaskName] = useState('');
  
  // 预览状态
  const [previewFiles, setPreviewFiles] = useState<string[]>([]);
  const [isScanning, setIsScanning] = useState(false);
  
  // 处理状态
  const [currentTask, setCurrentTask] = useState<BatchProcessingTask | null>(null);
  const [progress, setProgress] = useState<BatchProcessingProgress | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  
  // 数据加载
  const [templates, setTemplates] = useState<WorkflowTemplate[]>([]);
  const [supportedExtensions, setSupportedExtensions] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 加载数据
  useEffect(() => {
    if (isOpen) {
      loadInitialData();
    }
  }, [isOpen]);

  // 加载初始数据
  const loadInitialData = async () => {
    setLoading(true);
    try {
      // 加载工作流模板
      const templatesResult = await invoke<WorkflowTemplate[]>('get_workflow_templates');
      setTemplates(templatesResult);

      // 加载支持的文件扩展名
      const extensionsResult = await invoke<string[]>('get_supported_file_extensions');
      setSupportedExtensions(extensionsResult);

      // 设置默认模板
      if (templatesResult.length > 0) {
        setSelectedTemplate(templatesResult[0]);
      }
    } catch (err) {
      console.error('加载初始数据失败:', err);
      setError('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 选择输入文件夹
  const selectInputFolder = async () => {
    try {
      const result = await invoke<string | null>('select_folder', {
        title: '选择输入文件夹'
      });
      if (result) {
        setInputFolder(result);
        // 自动生成任务名称
        const folderName = result.split(/[/\\]/).pop() || 'batch_task';
        setTaskName(`批量处理_${folderName}_${new Date().toLocaleDateString()}`);
      }
    } catch (err) {
      console.error('选择文件夹失败:', err);
      setError('选择文件夹失败');
    }
  };

  // 选择输出文件夹
  const selectOutputFolder = async () => {
    try {
      const result = await invoke<string | null>('select_folder', {
        title: '选择输出文件夹'
      });
      if (result) {
        setOutputFolder(result);
        // 验证输出文件夹
        await invoke<boolean>('validate_output_folder', {
          folderPath: result
        });
      }
    } catch (err) {
      console.error('选择输出文件夹失败:', err);
      setError('选择或创建输出文件夹失败');
    }
  };

  // 扫描文件预览
  const scanFilesPreview = async () => {
    if (!inputFolder) {
      setError('请先选择输入文件夹');
      return;
    }

    setIsScanning(true);
    setError(null);
    
    try {
      const files = await invoke<string[]>('scan_folder_preview', {
        folderPath: inputFolder,
        fileExtensions: fileExtensions,
        recursive: recursive
      });
      
      setPreviewFiles(files);
      setStep('preview');
    } catch (err) {
      console.error('扫描文件失败:', err);
      setError('扫描文件失败');
    } finally {
      setIsScanning(false);
    }
  };

  // 开始批量处理
  const startBatchProcessing = async () => {
    if (!selectedTemplate || !inputFolder || !outputFolder) {
      setError('请完成所有配置');
      return;
    }

    setIsProcessing(true);
    setError(null);

    try {
      // 创建批量任务
      const request: CreateBatchTaskRequest = {
        name: taskName || '批量处理任务',
        workflow_template_id: selectedTemplate.id,
        input_folder: inputFolder,
        output_folder: outputFolder,
        file_extensions: fileExtensions,
        recursive: recursive
      };

      const task = await invoke<BatchProcessingTask>('create_batch_task', { request });
      setCurrentTask(task);

      // 开始处理
      await invoke('start_batch_processing', { taskId: task.id });
      
      setStep('processing');
      
      // 开始轮询进度
      startProgressPolling(task.id);
      
    } catch (err) {
      console.error('开始批量处理失败:', err);
      setError('开始批量处理失败');
      setIsProcessing(false);
    }
  };

  // 开始进度轮询
  const startProgressPolling = (taskId: string) => {
    const pollInterval = setInterval(async () => {
      try {
        const progressResult = await invoke<BatchProcessingProgress | null>('get_batch_progress', {
          taskId: taskId
        });
        
        if (progressResult) {
          setProgress(progressResult);
          
          // 如果任务完成，停止轮询
          if (progressResult.status === 'completed' || 
              progressResult.status === 'failed' || 
              progressResult.status === 'cancelled') {
            clearInterval(pollInterval);
            setIsProcessing(false);
            
            // 获取最终任务状态
            const finalTask = await invoke<BatchProcessingTask | null>('get_batch_task', {
              taskId: taskId
            });
            
            if (finalTask) {
              setCurrentTask(finalTask);
              if (onTaskComplete) {
                onTaskComplete(finalTask);
              }
            }
          }
        }
      } catch (err) {
        console.error('获取进度失败:', err);
        clearInterval(pollInterval);
        setIsProcessing(false);
      }
    }, 2000); // 每2秒轮询一次
  };

  // 取消任务
  const cancelTask = async () => {
    if (!currentTask) return;

    try {
      await invoke('cancel_batch_task', { taskId: currentTask.id });
      setIsProcessing(false);
    } catch (err) {
      console.error('取消任务失败:', err);
      setError('取消任务失败');
    }
  };

  // 重置状态
  const resetState = () => {
    setStep('config');
    setInputFolder('');
    setOutputFolder('');
    setSelectedTemplate(null);
    setFileExtensions(['jpg', 'png', 'jpeg']);
    setRecursive(true);
    setTaskName('');
    setPreviewFiles([]);
    setCurrentTask(null);
    setProgress(null);
    setIsProcessing(false);
    setError(null);
  };

  // 关闭处理
  const handleClose = () => {
    if (isProcessing) {
      if (confirm('任务正在处理中，确定要关闭吗？')) {
        if (currentTask) {
          cancelTask();
        }
        resetState();
        onClose();
      }
    } else {
      resetState();
      onClose();
    }
  };

  // 获取状态图标
  const getStatusIcon = (status: BatchTaskStatus) => {
    switch (status) {
      case 'pending':
        return <Clock className="w-4 h-4 text-gray-500" />;
      case 'processing':
        return <RotateCcw className="w-4 h-4 text-blue-500 animate-spin" />;
      case 'completed':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'failed':
        return <AlertCircle className="w-4 h-4 text-red-500" />;
      case 'cancelled':
        return <Square className="w-4 h-4 text-gray-500" />;
      default:
        return <Clock className="w-4 h-4 text-gray-500" />;
    }
  };

  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">
          <h2 className="text-xl font-semibold text-gray-900">
            批量文件夹处理
          </h2>
          <button
            onClick={handleClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* 步骤指示器 */}
        <div className="px-6 py-4 bg-gray-50 border-b border-gray-200">
          <div className="flex items-center space-x-4">
            <div className={`flex items-center space-x-2 ${step === 'config' ? 'text-blue-600' : step === 'preview' || step === 'processing' ? 'text-green-600' : 'text-gray-400'}`}>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${step === 'config' ? 'bg-blue-100' : step === 'preview' || step === 'processing' ? 'bg-green-100' : 'bg-gray-100'}`}>
                1
              </div>
              <span className="text-sm font-medium">配置</span>
            </div>
            <div className="flex-1 h-px bg-gray-300"></div>
            <div className={`flex items-center space-x-2 ${step === 'preview' ? 'text-blue-600' : step === 'processing' ? 'text-green-600' : 'text-gray-400'}`}>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${step === 'preview' ? 'bg-blue-100' : step === 'processing' ? 'bg-green-100' : 'bg-gray-100'}`}>
                2
              </div>
              <span className="text-sm font-medium">预览</span>
            </div>
            <div className="flex-1 h-px bg-gray-300"></div>
            <div className={`flex items-center space-x-2 ${step === 'processing' ? 'text-blue-600' : 'text-gray-400'}`}>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${step === 'processing' ? 'bg-blue-100' : 'bg-gray-100'}`}>
                3
              </div>
              <span className="text-sm font-medium">处理</span>
            </div>
          </div>
        </div>

        {/* 内容区域 */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-200px)]">
          {error && (
            <div className="mb-4 bg-red-50 border border-red-200 rounded-lg p-3">
              <div className="flex items-center space-x-2">
                <AlertCircle className="w-4 h-4 text-red-500" />
                <span className="text-sm text-red-700">{error}</span>
              </div>
            </div>
          )}

          {/* 配置步骤 */}
          {step === 'config' && (
            <div className="space-y-6">
              {/* 任务名称 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  任务名称
                </label>
                <input
                  type="text"
                  value={taskName}
                  onChange={(e) => setTaskName(e.target.value)}
                  placeholder="输入任务名称"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* 工作流模板选择 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  工作流模板
                </label>
                <select
                  value={selectedTemplate?.id || ''}
                  onChange={(e) => {
                    const template = templates.find(t => t.id === parseInt(e.target.value));
                    setSelectedTemplate(template || null);
                  }}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">选择工作流模板</option>
                  {templates.map(template => (
                    <option key={template.id} value={template.id}>
                      {template.name} v{template.version}
                    </option>
                  ))}
                </select>
              </div>

              {/* 文件夹选择 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    输入文件夹
                  </label>
                  <div className="flex space-x-2">
                    <input
                      type="text"
                      value={inputFolder}
                      readOnly
                      placeholder="选择输入文件夹"
                      className="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                    />
                    <button
                      onClick={selectInputFolder}
                      className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
                    >
                      <FolderOpen className="w-4 h-4" />
                      <span>选择</span>
                    </button>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    输出文件夹
                  </label>
                  <div className="flex space-x-2">
                    <input
                      type="text"
                      value={outputFolder}
                      readOnly
                      placeholder="选择输出文件夹"
                      className="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                    />
                    <button
                      onClick={selectOutputFolder}
                      className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
                    >
                      <FolderOpen className="w-4 h-4" />
                      <span>选择</span>
                    </button>
                  </div>
                </div>
              </div>

              {/* 文件类型和选项 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    文件类型
                  </label>
                  <div className="space-y-2">
                    {supportedExtensions.map(ext => (
                      <label key={ext} className="flex items-center space-x-2">
                        <input
                          type="checkbox"
                          checked={fileExtensions.includes(ext)}
                          onChange={(e) => {
                            if (e.target.checked) {
                              setFileExtensions([...fileExtensions, ext]);
                            } else {
                              setFileExtensions(fileExtensions.filter(e => e !== ext));
                            }
                          }}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <span className="text-sm text-gray-700">.{ext}</span>
                      </label>
                    ))}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    扫描选项
                  </label>
                  <label className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      checked={recursive}
                      onChange={(e) => setRecursive(e.target.checked)}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                    <span className="text-sm text-gray-700">包含子文件夹</span>
                  </label>
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-end space-x-3">
                <button
                  onClick={handleClose}
                  className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={scanFilesPreview}
                  disabled={!inputFolder || !selectedTemplate || isScanning}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400 transition-colors flex items-center space-x-2"
                >
                  {isScanning ? (
                    <>
                      <RotateCcw className="w-4 h-4 animate-spin" />
                      <span>扫描中...</span>
                    </>
                  ) : (
                    <>
                      <FileText className="w-4 h-4" />
                      <span>扫描预览</span>
                    </>
                  )}
                </button>
              </div>
            </div>
          )}

          {/* 预览步骤 */}
          {step === 'preview' && (
            <div className="space-y-6">
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="flex items-center space-x-2 mb-2">
                  <Image className="w-5 h-5 text-blue-600" />
                  <span className="font-medium text-blue-900">扫描结果</span>
                </div>
                <p className="text-sm text-blue-700">
                  在 <strong>{inputFolder}</strong> 中找到 <strong>{previewFiles.length}</strong> 个文件
                </p>
              </div>

              {/* 文件列表 */}
              <div className="border border-gray-200 rounded-lg">
                <div className="bg-gray-50 px-4 py-3 border-b border-gray-200">
                  <h3 className="text-sm font-medium text-gray-900">文件列表</h3>
                </div>
                <div className="max-h-60 overflow-y-auto">
                  {previewFiles.map((file, index) => (
                    <div key={index} className="px-4 py-2 border-b border-gray-100 last:border-b-0">
                      <div className="flex items-center space-x-2">
                        <Image className="w-4 h-4 text-gray-400" />
                        <span className="text-sm text-gray-700 truncate">{file}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-between">
                <button
                  onClick={() => setStep('config')}
                  className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  返回配置
                </button>
                <div className="flex space-x-3">
                  <button
                    onClick={handleClose}
                    className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    取消
                  </button>
                  <button
                    onClick={startBatchProcessing}
                    disabled={previewFiles.length === 0 || isProcessing}
                    className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:bg-gray-400 transition-colors flex items-center space-x-2"
                  >
                    <Play className="w-4 h-4" />
                    <span>开始处理</span>
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* 处理步骤 */}
          {step === 'processing' && currentTask && (
            <div className="space-y-6">
              {/* 任务信息 */}
              <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center space-x-2">
                    {getStatusIcon(currentTask.status)}
                    <span className="font-medium text-gray-900">{currentTask.name}</span>
                  </div>
                  <span className="text-sm text-gray-500">
                    {currentTask.status === 'processing' ? '处理中' : 
                     currentTask.status === 'completed' ? '已完成' :
                     currentTask.status === 'failed' ? '失败' : '已取消'}
                  </span>
                </div>
                
                {progress && (
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm text-gray-600">
                      <span>进度: {progress.processed_files} / {progress.total_files}</span>
                      <span>{progress.progress_percentage.toFixed(1)}%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div 
                        className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                        style={{ width: `${progress.progress_percentage}%` }}
                      ></div>
                    </div>
                    {progress.failed_files > 0 && (
                      <div className="text-sm text-red-600">
                        失败: {progress.failed_files} 个文件
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-end space-x-3">
                {isProcessing ? (
                  <button
                    onClick={cancelTask}
                    className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center space-x-2"
                  >
                    <Square className="w-4 h-4" />
                    <span>取消任务</span>
                  </button>
                ) : (
                  <button
                    onClick={handleClose}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    完成
                  </button>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
