/**
 * 工作流页面
 * 
 * 多工作流系统的主页面，提供工作流列表、执行和管理功能
 * 遵循Tauri开发规范的页面设计原则
 */

import React, { useState } from 'react';
import { Settings, History, Plus, Activity, Download } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { WorkflowList } from '../components/workflow/WorkflowList';
import { WorkflowExecutionModal } from '../components/workflow/WorkflowExecutionModal';
import { WorkflowDetailModal } from '../components/workflow/WorkflowDetailModal';
import { ExecutionHistoryList } from '../components/workflow/ExecutionHistoryList';
import { ExecutionDetailViewer } from '../components/workflow/ExecutionDetailViewer';
import { EnvironmentList } from '../components/workflow/EnvironmentList';
import { EnvironmentConfigurator } from '../components/workflow/EnvironmentConfigurator';
import { MonitoringDashboard } from '../components/workflow/MonitoringDashboard';
import { WorkflowCreator } from '../components/workflow/WorkflowCreator';
import { BatchOperationManager } from '../components/workflow/BatchOperationManager';
import { SimpleExportModal } from '../components/workflow/SimpleExportModal';
import type {
  WorkflowTemplate,
  WorkflowExecutionRecord,
  WorkflowExecutionEnvironment,
  CreateEnvironmentRequest
} from '../types/workflow';

// 所有类型定义现在从 ../types/workflow 导入

/**
 * 工作流页面组件
 */
export const WorkflowPage: React.FC = () => {
  const [selectedWorkflow, setSelectedWorkflow] = useState<WorkflowTemplate | null>(null);
  const [isExecutionModalOpen, setIsExecutionModalOpen] = useState(false);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [activeTab, setActiveTab] = useState<'workflows' | 'history' | 'environments' | 'monitoring'>('workflows');

  // 执行历史相关状态
  const [selectedExecutionRecord, setSelectedExecutionRecord] = useState<WorkflowExecutionRecord | null>(null);
  const [isDetailViewerOpen, setIsDetailViewerOpen] = useState(false);

  // 环境管理相关状态
  const [selectedEnvironment, setSelectedEnvironment] = useState<WorkflowExecutionEnvironment | null>(null);
  const [isEnvironmentConfiguratorOpen, setIsEnvironmentConfiguratorOpen] = useState(false);

  // 工作流创建相关状态
  const [selectedWorkflowTemplate, setSelectedWorkflowTemplate] = useState<WorkflowTemplate | null>(null);
  const [isWorkflowCreatorOpen, setIsWorkflowCreatorOpen] = useState(false);

  // 批量操作相关状态
  const [selectedWorkflows, setSelectedWorkflows] = useState<WorkflowTemplate[]>([]);
  const [selectedExecutions, setSelectedExecutions] = useState<WorkflowExecutionRecord[]>([]);
  const [showBatchOperations, setShowBatchOperations] = useState(false);

  // 简化导出相关状态
  const [isSimpleExportModalOpen, setIsSimpleExportModalOpen] = useState(false);

  // 处理工作流选择（显示详情）
  const handleSelectWorkflow = (workflow: WorkflowTemplate) => {
    setSelectedWorkflow(workflow);
    setIsDetailModalOpen(true);
  };

  // 处理工作流执行
  const handleExecuteWorkflow = (workflow: WorkflowTemplate) => {
    setSelectedWorkflow(workflow);
    setIsExecutionModalOpen(true);
  };

  // 处理工作流编辑 - 将在后面重新定义

  // 关闭执行模态框
  const handleCloseExecutionModal = () => {
    setIsExecutionModalOpen(false);
    setSelectedWorkflow(null);
  };

  // 关闭详情模态框
  const handleCloseDetailModal = () => {
    setIsDetailModalOpen(false);
    setSelectedWorkflow(null);
  };

  // 从详情模态框执行工作流
  const handleExecuteFromDetail = (workflow: WorkflowTemplate) => {
    setIsDetailModalOpen(false);
    setSelectedWorkflow(workflow);
    setIsExecutionModalOpen(true);
  };

  // 执行历史相关处理函数
  const handleViewExecutionDetails = (record: WorkflowExecutionRecord) => {
    setSelectedExecutionRecord(record);
    setIsDetailViewerOpen(true);
  };

  const handleRetryExecution = async (record: WorkflowExecutionRecord) => {
    try {
      // TODO: 实现重试逻辑
      console.log('重试执行:', record);
    } catch (error) {
      console.error('重试失败:', error);
    }
  };

  const handleDeleteExecution = async (recordId: number) => {
    try {
      // TODO: 实现删除逻辑
      console.log('删除执行记录:', recordId);
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  const handleBatchDeleteExecutions = async (recordIds: number[]) => {
    try {
      // TODO: 实现批量删除逻辑
      console.log('批量删除执行记录:', recordIds);
    } catch (error) {
      console.error('批量删除失败:', error);
    }
  };

  const handleDownloadExecutionResult = async (record: WorkflowExecutionRecord) => {
    try {
      // TODO: 实现下载逻辑
      console.log('下载执行结果:', record);
    } catch (error) {
      console.error('下载失败:', error);
    }
  };

  const handleCloseDetailViewer = () => {
    setIsDetailViewerOpen(false);
    setSelectedExecutionRecord(null);
  };

  // 环境管理相关处理函数
  const handleAddEnvironment = () => {
    setSelectedEnvironment(null);
    setIsEnvironmentConfiguratorOpen(true);
  };

  const handleEditEnvironment = (env: WorkflowExecutionEnvironment) => {
    console.log('编辑环境，接收到的数据:', env);
    console.log('环境类型:', env.environment_type, '类型:', typeof env.environment_type);
    setSelectedEnvironment(env);
    setIsEnvironmentConfiguratorOpen(true);
  };

  const handleDeleteEnvironment = async (envId: number) => {
    try {
      // 确认删除
      const confirmed = window.confirm('确定要删除这个执行环境吗？此操作不可撤销。');
      if (!confirmed) return;

      console.log('删除执行环境:', envId);
      await invoke('delete_execution_environment', { id: envId });

      console.log('环境删除成功');
      // 刷新页面以显示最新数据
      window.location.reload();
    } catch (error) {
      console.error('删除环境失败:', error);
      alert(`删除环境失败: ${error}`);
    }
  };

  const handleHealthCheckEnvironment = async (envId: number) => {
    try {
      console.log('健康检查环境:', envId);
      // 调用健康检查命令
      const healthStatus = await invoke('health_check_execution_environment', { id: envId });
      console.log('健康检查完成，状态:', healthStatus);

      // 刷新页面以显示最新的健康状态
      window.location.reload();
    } catch (error) {
      console.error('健康检查失败:', error);
      alert(`健康检查失败: ${error}`);
    }
  };

  const handleToggleEnvironmentActive = async (envId: number, isActive: boolean) => {
    try {
      console.log('切换环境激活状态:', envId, isActive);
      const updatedEnvironment = await invoke('update_execution_environment', {
        id: envId,
        request: {
          is_active: isActive
        }
      });
      console.log('激活状态切换成功:', updatedEnvironment);

      // 刷新页面以显示最新状态
      window.location.reload();
    } catch (error) {
      console.error('切换激活状态失败:', error);
      alert(`切换激活状态失败: ${error}`);
    }
  };

  const handleSaveEnvironment = async (envData: CreateEnvironmentRequest) => {
    try {
      if (selectedEnvironment) {
        // 更新现有环境 - 简化逻辑，直接传递所有字段
        console.log('更新环境:', envData);
        const updateRequest = {
          name: envData.name,
          description: envData.description,
          base_url: envData.base_url,
          api_key: envData.api_key,
          connection_config_json: envData.connection_config_json,
          supported_workflow_types: envData.supported_workflow_types,
          max_concurrent_jobs: envData.max_concurrent_jobs,
          priority: envData.priority,
          max_memory_mb: envData.max_memory_mb,
          max_execution_time_seconds: envData.max_execution_time_seconds,
          metadata_json: envData.metadata_json,
          tags: envData.tags,
        };

        console.log('发送更新请求:', updateRequest);
        const updatedEnvironment = await invoke('update_execution_environment', {
          id: selectedEnvironment.id,
          request: updateRequest
        });
        console.log('更新成功，返回数据:', updatedEnvironment);
      } else {
        // 创建新环境
        console.log('创建环境:', envData);
        await invoke('create_execution_environment', { request: envData });
      }

      setIsEnvironmentConfiguratorOpen(false);
      setSelectedEnvironment(null);

      // TODO: 添加成功提示
      console.log('环境保存成功');

      // 刷新页面以显示最新数据（临时方案）
      window.location.reload();
    } catch (error) {
      console.error('保存环境失败:', error);
      // TODO: 添加错误提示UI
      alert(`保存环境失败: ${error}`);
    }
  };

  const handleCloseEnvironmentConfigurator = () => {
    setIsEnvironmentConfiguratorOpen(false);
    setSelectedEnvironment(null);
  };

  // 工作流创建相关处理函数
  const handleCreateWorkflow = () => {
    setSelectedWorkflowTemplate(null);
    setIsWorkflowCreatorOpen(true);
  };

  const handleEditWorkflow = (template: WorkflowTemplate) => {
    setSelectedWorkflowTemplate(template);
    setIsWorkflowCreatorOpen(true);
  };

  const handleSaveWorkflow = async (workflowData: any) => {
    try {
      if (selectedWorkflowTemplate) {
        // 更新现有工作流模板
        console.log('更新工作流:', workflowData);
        await invoke('update_workflow_template', {
          id: selectedWorkflowTemplate.id,
          request: {
            name: workflowData.name !== selectedWorkflowTemplate.name ? workflowData.name : undefined,
            description: workflowData.description !== selectedWorkflowTemplate.description ? workflowData.description : undefined,
            comfyui_workflow_json: JSON.stringify(workflowData.comfyui_workflow_json) !== JSON.stringify(selectedWorkflowTemplate.comfyui_workflow_json) ? workflowData.comfyui_workflow_json : undefined,
            ui_config_json: JSON.stringify(workflowData.ui_config_json) !== JSON.stringify(selectedWorkflowTemplate.ui_config_json) ? workflowData.ui_config_json : undefined,
            execution_config_json: workflowData.execution_config_json,
            input_schema_json: workflowData.input_schema_json,
            output_schema_json: workflowData.output_schema_json,
            tags: workflowData.tags,
            category: workflowData.category,
            author: workflowData.author,
          }
        });
        console.log('工作流模板更新成功');
      } else {
        // 创建新工作流模板
        console.log('创建工作流:', workflowData);
        await invoke('create_workflow_template', {
          request: workflowData
        });
        console.log('工作流模板创建成功');
      }
      setIsWorkflowCreatorOpen(false);
      setSelectedWorkflowTemplate(null);
      // 刷新工作流列表
      window.location.reload();
    } catch (error) {
      console.error('保存工作流失败:', error);
      alert(`保存工作流失败: ${error}`);
    }
  };

  const handleCloseWorkflowCreator = () => {
    setIsWorkflowCreatorOpen(false);
    setSelectedWorkflowTemplate(null);
  };

  // 批量操作相关处理函数
  const handleWorkflowSelectionChange = (workflows: WorkflowTemplate[]) => {
    setSelectedWorkflows(workflows);
    setShowBatchOperations(workflows.length > 0);
  };

  // const handleExecutionSelectionChange = (executions: WorkflowExecutionRecord[]) => {
  //   setSelectedExecutions(executions);
  //   setShowBatchOperations(executions.length > 0);
  // };

  const handleBatchOperationComplete = (task: any) => {
    console.log('批量操作完成:', task);
    // 刷新相关数据
    setSelectedWorkflows([]);
    setSelectedExecutions([]);
    setShowBatchOperations(false);
  };

  const handleCloseBatchOperations = () => {
    setShowBatchOperations(false);
  };

  // 简化导出相关处理函数
  const handleOpenSimpleExport = () => {
    setIsSimpleExportModalOpen(true);
  };

  const handleCloseSimpleExport = () => {
    setIsSimpleExportModalOpen(false);
  };

  return (
    <div className="min-h-screen">
      {/* 页面头部 */}
      <div className="">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="page-header flex items-center justify-between h-16">
            <div className='py-4'>
              <h1 className="text-2xl font-bold text-gray-900">
                AI工作流
              </h1>
              <p className="text-sm text-gray-600 mt-1">
                管理和执行各种AI生成任务
              </p>
            </div>

            <div className="flex items-center space-x-4">
              
            </div>
          </div>
        </div>
      </div>

      {/* 标签导航 */}
      <div className="bg-white border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <nav className="flex space-x-8">
            <button
              onClick={() => setActiveTab('workflows')}
              className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors ${activeTab === 'workflows'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
            >
              工作流列表
            </button>

            <button
              onClick={() => setActiveTab('history')}
              className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors flex items-center space-x-2 ${activeTab === 'history'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
            >
              <History className="w-4 h-4" />
              <span>执行历史</span>
            </button>

            <button
              onClick={() => setActiveTab('environments')}
              className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors flex items-center space-x-2 ${activeTab === 'environments'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
            >
              <Settings className="w-4 h-4" />
              <span>执行环境</span>
            </button>

            <button
              onClick={() => setActiveTab('monitoring')}
              className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors flex items-center space-x-2 ${activeTab === 'monitoring'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
            >
              <Activity className="w-4 h-4" />
              <span>实时监控</span>
            </button>
          </nav>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {activeTab === 'workflows' && (
          <div>
            <div className="mb-6 flex items-center justify-between">
              <div>
                <h2 className="text-lg font-medium text-gray-900 mb-2">
                  可用工作流
                </h2>
                <p className="text-sm text-gray-600">
                  选择一个工作流开始AI生成任务，或管理现有的工作流模板
                </p>
              </div>
              <div className="flex items-center space-x-2">
                <button
                  onClick={handleOpenSimpleExport}
                  className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center space-x-2"
                >
                  <Download className="w-4 h-4" />
                  <span>导入导出</span>
                </button>

                <button
                  onClick={handleCreateWorkflow}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
                >
                  <Plus className="w-4 h-4" />
                  <span>创建工作流</span>
                </button>
              </div>
            </div>

            <WorkflowList
              onSelectWorkflow={handleSelectWorkflow}
              onExecuteWorkflow={handleExecuteWorkflow}
              onEditWorkflow={handleEditWorkflow}
              showManagement={true}
              enableBatchSelection={true}
              selectedWorkflows={selectedWorkflows}
              onSelectionChange={handleWorkflowSelectionChange}
            />
          </div>
        )}

        {activeTab === 'history' && (
          <div>
            <div className="mb-6 flex items-center justify-between">
              <div>
                <h2 className="text-lg font-medium text-gray-900 mb-2">
                  执行历史
                </h2>
                <p className="text-sm text-gray-600">
                  查看所有工作流的执行记录和结果
                </p>
              </div>
              <button
                onClick={handleOpenSimpleExport}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center space-x-2"
              >
                <Download className="w-4 h-4" />
                <span>导入导出</span>
              </button>
            </div>

            <ExecutionHistoryList
              onViewDetails={handleViewExecutionDetails}
              onRetry={handleRetryExecution}
              onDelete={handleDeleteExecution}
              onBatchDelete={handleBatchDeleteExecutions}
              onDownload={handleDownloadExecutionResult}
            />

            {/* 批量操作面板 */}
            {showBatchOperations && (selectedWorkflows.length > 0 || selectedExecutions.length > 0) && (
              <div className="mt-6">
                <BatchOperationManager
                  selectedTemplates={selectedWorkflows}
                  selectedExecutions={selectedExecutions}
                  onOperationComplete={handleBatchOperationComplete}
                  onClose={handleCloseBatchOperations}
                />
              </div>
            )}
          </div>
        )}

        {activeTab === 'environments' && (
          <div>
            <div className="mb-6">
              <h2 className="text-lg font-medium text-gray-900 mb-2">
                执行环境
              </h2>
              <p className="text-sm text-gray-600">
                管理AI工作流的执行环境，包括本地ComfyUI和云端服务
              </p>
            </div>

            <EnvironmentList
              onAdd={handleAddEnvironment}
              onEdit={handleEditEnvironment}
              onDelete={handleDeleteEnvironment}
              onHealthCheck={handleHealthCheckEnvironment}
              onToggleActive={handleToggleEnvironmentActive}
            />
          </div>
        )}

        {activeTab === 'monitoring' && (
          <div>
            <div className="mb-6">
              <h2 className="text-lg font-medium text-gray-900 mb-2">
                实时监控
              </h2>
              <p className="text-sm text-gray-600">
                监控系统状态和活跃的工作流执行情况
              </p>
            </div>

            <MonitoringDashboard
              onViewExecutionDetails={handleViewExecutionDetails}
              refreshInterval={3000}
            />
          </div>
        )}
      </div>

      {/* 工作流执行模态框 */}
      <WorkflowExecutionModal
        isOpen={isExecutionModalOpen}
        onClose={handleCloseExecutionModal}
        workflow={selectedWorkflow}
      />

      {/* 工作流详情模态框 */}
      <WorkflowDetailModal
        workflow={selectedWorkflow}
        isOpen={isDetailModalOpen}
        onClose={handleCloseDetailModal}
        onExecute={handleExecuteFromDetail}
        onEdit={handleEditWorkflow}
      />

      {/* 执行详情查看器 */}
      {selectedExecutionRecord && (
        <ExecutionDetailViewer
          record={selectedExecutionRecord}
          isOpen={isDetailViewerOpen}
          onClose={handleCloseDetailViewer}
          onDownload={handleDownloadExecutionResult}
          onRetry={handleRetryExecution}
        />
      )}

      {/* 环境配置器 */}
      <EnvironmentConfigurator
        environment={selectedEnvironment || undefined}
        isOpen={isEnvironmentConfiguratorOpen}
        onSave={handleSaveEnvironment}
        onClose={handleCloseEnvironmentConfigurator}
      />

      {/* 工作流创建器 */}
      <WorkflowCreator
        isOpen={isWorkflowCreatorOpen}
        onClose={handleCloseWorkflowCreator}
        onSave={handleSaveWorkflow}
        editingTemplate={selectedWorkflowTemplate || undefined}
      />

      {/* 简化导出模态框 */}
      <SimpleExportModal
        isOpen={isSimpleExportModalOpen}
        onClose={handleCloseSimpleExport}
        selectedTemplates={selectedWorkflows}
        selectedEnvironments={[]} // 暂时为空，后续可以添加环境选择
      />
    </div>
  );
};
