/**
 * ComfyUI V2 状态管理
 * 基于 Zustand 的现代化状态管理，支持实时更新和类型安全
 */

import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { ComfyUIV2Service } from '../services/comfyuiV2Service';
import type {
  ComfyUIV2Config,
  ConnectionStatus,
  SystemInfo,
  QueueStatus,
  WorkflowV2,
  TemplateV2,
  ExecutionV2,
  RealtimeEvent,
  ExecutionCompletedEvent,
  ExecutionProgressEvent,
} from '../services/comfyuiV2Service';

// ==================== 状态接口定义 ====================

interface ComfyUIV2State {
  // ==================== 连接状态 ====================
  isConnected: boolean;
  connectionStatus: ConnectionStatus | null;
  systemInfo: SystemInfo | null;
  queueStatus: QueueStatus | null;
  config: ComfyUIV2Config | null;
  
  // ==================== 工作流状态 ====================
  workflows: WorkflowV2[];
  currentWorkflow: WorkflowV2 | null;
  workflowsLoading: boolean;
  workflowsError: string | null;
  
  // ==================== 模板状态 ====================
  templates: TemplateV2[];
  currentTemplate: TemplateV2 | null;
  templatesLoading: boolean;
  templatesError: string | null;
  
  // ==================== 执行状态 ====================
  executions: ExecutionV2[];
  currentExecution: ExecutionV2 | null;
  executionsLoading: boolean;
  executionsError: string | null;
  
  // ==================== 实时状态 ====================
  realtimeConnected: boolean;
  realtimeEvents: RealtimeEvent[];
  realtimeSubscriptionId: string | null;
  
  // ==================== UI 状态 ====================
  selectedWorkflowIds: string[];
  selectedTemplateIds: string[];
  selectedExecutionIds: string[];
  
  // ==================== 过滤和搜索 ====================
  workflowFilters: {
    category?: string;
    tags?: string[];
    searchQuery?: string;
  };
  templateFilters: {
    category?: string;
    tags?: string[];
    searchQuery?: string;
  };
  executionFilters: {
    status?: string;
    workflowId?: string;
    templateId?: string;
  };
}

interface ComfyUIV2Actions {
  // ==================== 连接管理 ====================
  connect: (config: ComfyUIV2Config) => Promise<void>;
  disconnect: () => Promise<void>;
  refreshConnectionStatus: () => Promise<void>;
  refreshSystemInfo: () => Promise<void>;
  refreshQueueStatus: () => Promise<void>;
  loadConfig: () => Promise<void>;
  updateConfig: (config: Partial<ComfyUIV2Config>) => Promise<void>;
  
  // ==================== 工作流管理 ====================
  loadWorkflows: () => Promise<void>;
  createWorkflow: (request: any) => Promise<WorkflowV2>;
  updateWorkflow: (id: string, request: any) => Promise<WorkflowV2>;
  deleteWorkflow: (id: string) => Promise<void>;
  setCurrentWorkflow: (workflow: WorkflowV2 | null) => void;
  searchWorkflows: (query: string, category?: string) => Promise<void>;
  setWorkflowFilters: (filters: Partial<ComfyUIV2State['workflowFilters']>) => void;
  
  // ==================== 模板管理 ====================
  loadTemplates: () => Promise<void>;
  createTemplate: (request: any) => Promise<TemplateV2>;
  updateTemplate: (id: string, request: any) => Promise<TemplateV2>;
  deleteTemplate: (id: string) => Promise<void>;
  setCurrentTemplate: (template: TemplateV2 | null) => void;
  setTemplateFilters: (filters: Partial<ComfyUIV2State['templateFilters']>) => void;
  
  // ==================== 执行管理 ====================
  loadExecutions: () => Promise<void>;
  executeWorkflow: (request: any) => Promise<ExecutionV2>;
  executeTemplate: (request: any) => Promise<ExecutionV2>;
  cancelExecution: (executionId: string) => Promise<void>;
  setCurrentExecution: (execution: ExecutionV2 | null) => void;
  setExecutionFilters: (filters: Partial<ComfyUIV2State['executionFilters']>) => void;
  
  // ==================== 实时通信 ====================
  startRealtimeMonitor: () => Promise<void>;
  stopRealtimeMonitor: () => Promise<void>;
  subscribeRealtimeEvents: () => Promise<void>;
  unsubscribeRealtimeEvents: () => Promise<void>;
  addRealtimeEvent: (event: RealtimeEvent) => void;
  clearRealtimeEvents: () => void;
  
  // ==================== 选择管理 ====================
  selectWorkflow: (id: string) => void;
  deselectWorkflow: (id: string) => void;
  selectAllWorkflows: () => void;
  clearWorkflowSelection: () => void;
  selectTemplate: (id: string) => void;
  deselectTemplate: (id: string) => void;
  selectAllTemplates: () => void;
  clearTemplateSelection: () => void;
  selectExecution: (id: string) => void;
  deselectExecution: (id: string) => void;
  clearExecutionSelection: () => void;
  
  // ==================== 重置和清理 ====================
  reset: () => void;
  cleanup: () => void;
}

type ComfyUIV2Store = ComfyUIV2State & ComfyUIV2Actions;

// ==================== 初始状态 ====================

const initialState: ComfyUIV2State = {
  // 连接状态
  isConnected: false,
  connectionStatus: null,
  systemInfo: null,
  queueStatus: null,
  config: null,
  
  // 工作流状态
  workflows: [],
  currentWorkflow: null,
  workflowsLoading: false,
  workflowsError: null,
  
  // 模板状态
  templates: [],
  currentTemplate: null,
  templatesLoading: false,
  templatesError: null,
  
  // 执行状态
  executions: [],
  currentExecution: null,
  executionsLoading: false,
  executionsError: null,
  
  // 实时状态
  realtimeConnected: false,
  realtimeEvents: [],
  realtimeSubscriptionId: null,
  
  // UI 状态
  selectedWorkflowIds: [],
  selectedTemplateIds: [],
  selectedExecutionIds: [],
  
  // 过滤状态
  workflowFilters: {},
  templateFilters: {},
  executionFilters: {},
};

// ==================== Zustand Store ====================

export const useComfyUIV2Store = create<ComfyUIV2Store>()(
  subscribeWithSelector((set, get) => ({
    ...initialState,

    // ==================== 连接管理 ====================
    
    connect: async (config: ComfyUIV2Config) => {
      try {
        // 先更新配置，然后连接
        await ComfyUIV2Service.updateConfig(config);
        await ComfyUIV2Service.connect(config);
        set({
          isConnected: true,
          config,
          connectionStatus: await ComfyUIV2Service.getConnectionStatus()
        });

        // 连接成功后加载基础数据
        const { refreshSystemInfo, refreshQueueStatus, loadWorkflows, loadTemplates } = get();
        await Promise.all([
          refreshSystemInfo(),
          refreshQueueStatus(),
          loadWorkflows(),
          loadTemplates(),
        ]);
      } catch (error) {
        set({ isConnected: false });
        throw error;
      }
    },

    disconnect: async () => {
      try {
        await ComfyUIV2Service.disconnect();
        const { stopRealtimeMonitor } = get();
        await stopRealtimeMonitor();
        set({ 
          isConnected: false,
          connectionStatus: null,
          systemInfo: null,
          queueStatus: null,
        });
      } catch (error) {
        console.error('Disconnect error:', error);
        throw error;
      }
    },

    refreshConnectionStatus: async () => {
      try {
        const status = await ComfyUIV2Service.getConnectionStatus();
        set({ 
          connectionStatus: status,
          isConnected: status.connected 
        });
      } catch (error) {
        console.error('Failed to refresh connection status:', error);
      }
    },

    refreshSystemInfo: async () => {
      try {
        const systemInfo = await ComfyUIV2Service.getSystemInfo();
        set({ systemInfo });
      } catch (error) {
        console.error('Failed to refresh system info:', error);
      }
    },

    refreshQueueStatus: async () => {
      try {
        const queueStatus = await ComfyUIV2Service.getQueueStatus();
        set({ queueStatus });
      } catch (error) {
        console.error('Failed to refresh queue status:', error);
      }
    },

    loadConfig: async () => {
      try {
        const config = await ComfyUIV2Service.getConfig();
        set({ config });
      } catch (error) {
        console.error('Failed to load config:', error);
        // 如果加载失败，使用默认配置
        const defaultConfig: ComfyUIV2Config = {
          base_url: 'http://192.168.0.193:8188',
          timeout: 30000,
          retry_attempts: 3,
          enable_cache: true,
          max_concurrency: 4,
          websocket_url: 'ws://192.168.0.193:8188/ws',
        };
        set({ config: defaultConfig });
      }
    },

    updateConfig: async (configUpdate: Partial<ComfyUIV2Config>) => {
      try {
        await ComfyUIV2Service.updateConfig(configUpdate);
        const currentConfig = get().config;
        if (currentConfig) {
          set({ config: { ...currentConfig, ...configUpdate } });
        }
      } catch (error) {
        console.error('Failed to update config:', error);
        throw error;
      }
    },

    // ==================== 工作流管理 ====================
    
    loadWorkflows: async () => {
      set({ workflowsLoading: true, workflowsError: null });
      try {
        const workflows = await ComfyUIV2Service.listWorkflows();
        set({ workflows, workflowsLoading: false });
      } catch (error) {
        set({ 
          workflowsLoading: false, 
          workflowsError: error instanceof Error ? error.message : '加载工作流失败' 
        });
        throw error;
      }
    },

    createWorkflow: async (request: any) => {
      try {
        const workflow = await ComfyUIV2Service.createWorkflow(request);
        set(state => ({ 
          workflows: [...state.workflows, workflow] 
        }));
        return workflow;
      } catch (error) {
        console.error('Failed to create workflow:', error);
        throw error;
      }
    },

    updateWorkflow: async (id: string, request: any) => {
      try {
        const updatedWorkflow = await ComfyUIV2Service.updateWorkflow(id, request);
        set(state => ({
          workflows: state.workflows.map(w => w.id === id ? updatedWorkflow : w),
          currentWorkflow: state.currentWorkflow?.id === id ? updatedWorkflow : state.currentWorkflow
        }));
        return updatedWorkflow;
      } catch (error) {
        console.error('Failed to update workflow:', error);
        throw error;
      }
    },

    deleteWorkflow: async (id: string) => {
      try {
        await ComfyUIV2Service.deleteWorkflow(id);
        set(state => ({
          workflows: state.workflows.filter(w => w.id !== id),
          currentWorkflow: state.currentWorkflow?.id === id ? null : state.currentWorkflow,
          selectedWorkflowIds: state.selectedWorkflowIds.filter(wId => wId !== id)
        }));
      } catch (error) {
        console.error('Failed to delete workflow:', error);
        throw error;
      }
    },

    setCurrentWorkflow: (workflow: WorkflowV2 | null) => {
      set({ currentWorkflow: workflow });
    },

    searchWorkflows: async (query: string, category?: string) => {
      set({ workflowsLoading: true, workflowsError: null });
      try {
        const workflows = await ComfyUIV2Service.searchWorkflows(query, category);
        set({ workflows, workflowsLoading: false });
      } catch (error) {
        set({ 
          workflowsLoading: false, 
          workflowsError: error instanceof Error ? error.message : '搜索工作流失败' 
        });
        throw error;
      }
    },

    setWorkflowFilters: (filters: Partial<ComfyUIV2State['workflowFilters']>) => {
      set(state => ({
        workflowFilters: { ...state.workflowFilters, ...filters }
      }));
    },

    // ==================== 模板管理 ====================
    
    loadTemplates: async () => {
      set({ templatesLoading: true, templatesError: null });
      try {
        const templates = await ComfyUIV2Service.listTemplates();
        set({ templates, templatesLoading: false });
      } catch (error) {
        set({ 
          templatesLoading: false, 
          templatesError: error instanceof Error ? error.message : '加载模板失败' 
        });
        throw error;
      }
    },

    createTemplate: async (request: any) => {
      try {
        const template = await ComfyUIV2Service.createTemplate(request);
        set(state => ({ 
          templates: [...state.templates, template] 
        }));
        return template;
      } catch (error) {
        console.error('Failed to create template:', error);
        throw error;
      }
    },

    updateTemplate: async (id: string, request: any) => {
      try {
        const updatedTemplate = await ComfyUIV2Service.updateTemplate(id, request);
        set(state => ({
          templates: state.templates.map(t => t.id === id ? updatedTemplate : t),
          currentTemplate: state.currentTemplate?.id === id ? updatedTemplate : state.currentTemplate
        }));
        return updatedTemplate;
      } catch (error) {
        console.error('Failed to update template:', error);
        throw error;
      }
    },

    deleteTemplate: async (id: string) => {
      try {
        await ComfyUIV2Service.deleteTemplate(id);
        set(state => ({
          templates: state.templates.filter(t => t.id !== id),
          currentTemplate: state.currentTemplate?.id === id ? null : state.currentTemplate,
          selectedTemplateIds: state.selectedTemplateIds.filter(tId => tId !== id)
        }));
      } catch (error) {
        console.error('Failed to delete template:', error);
        throw error;
      }
    },

    setCurrentTemplate: (template: TemplateV2 | null) => {
      set({ currentTemplate: template });
    },

    setTemplateFilters: (filters: Partial<ComfyUIV2State['templateFilters']>) => {
      set(state => ({
        templateFilters: { ...state.templateFilters, ...filters }
      }));
    },

    // ==================== 执行管理 ====================
    
    loadExecutions: async () => {
      set({ executionsLoading: true, executionsError: null });
      try {
        const executions = await ComfyUIV2Service.getExecutionHistory();
        set({ executions, executionsLoading: false });
      } catch (error) {
        set({ 
          executionsLoading: false, 
          executionsError: error instanceof Error ? error.message : '加载执行历史失败' 
        });
        throw error;
      }
    },

    executeWorkflow: async (request: any) => {
      try {
        const execution = await ComfyUIV2Service.executeWorkflow(request);
        set(state => ({
          executions: [execution, ...state.executions],
          currentExecution: execution
        }));

        // 注册执行映射以便实时跟踪
        await ComfyUIV2Service.registerExecutionMapping(execution.prompt_id, execution.id);

        return execution;
      } catch (error) {
        console.error('Failed to execute workflow:', error);
        throw error;
      }
    },

    // ==================== 调试功能 ====================

    createTestWorkflow: async () => {
      try {
        // 创建一个简单的测试工作流
        const testWorkflow = {
          name: `测试工作流_${Date.now()}`,
          description: '用于测试的简单工作流',
          workflow_json: {
            "1": {
              "inputs": {
                "text": "Hello, ComfyUI!"
              },
              "class_type": "CLIPTextEncode",
              "_meta": {
                "title": "CLIP Text Encode (Prompt)"
              }
            }
          },
          tags: ['test', 'debug']
        };

        const result = await ComfyUIV2Service.createWorkflow(testWorkflow);

        // 刷新工作流列表
        await get().loadWorkflows();

        return result;
      } catch (error) {
        console.error('Failed to create test workflow:', error);
        throw error;
      }
    },

    debugListWorkflows: async () => {
      try {
        const workflows = await ComfyUIV2Service.debugListWorkflows();
        console.log('调试工作流列表:', workflows);
        return workflows;
      } catch (error) {
        console.error('Failed to debug list workflows:', error);
        throw error;
      }
    },

    executeTemplate: async (request: any) => {
      try {
        const execution = await ComfyUIV2Service.executeTemplate(request);
        set(state => ({ 
          executions: [execution, ...state.executions],
          currentExecution: execution
        }));
        
        // 注册执行映射以便实时跟踪
        await ComfyUIV2Service.registerExecutionMapping(execution.prompt_id, execution.id);
        
        return execution;
      } catch (error) {
        console.error('Failed to execute template:', error);
        throw error;
      }
    },

    cancelExecution: async (executionId: string) => {
      try {
        await ComfyUIV2Service.cancelExecution(executionId);
        set(state => ({
          executions: state.executions.map(e => 
            e.id === executionId ? { ...e, status: 'cancelled' as const } : e
          )
        }));
      } catch (error) {
        console.error('Failed to cancel execution:', error);
        throw error;
      }
    },

    setCurrentExecution: (execution: ExecutionV2 | null) => {
      set({ currentExecution: execution });
    },

    setExecutionFilters: (filters: Partial<ComfyUIV2State['executionFilters']>) => {
      set(state => ({
        executionFilters: { ...state.executionFilters, ...filters }
      }));
    },

    // ==================== 实时通信 ====================
    
    startRealtimeMonitor: async () => {
      try {
        await ComfyUIV2Service.startRealtimeMonitor();
        set({ realtimeConnected: true });
      } catch (error) {
        console.error('Failed to start realtime monitor:', error);
        throw error;
      }
    },

    stopRealtimeMonitor: async () => {
      try {
        await ComfyUIV2Service.stopRealtimeMonitor();
        const { unsubscribeRealtimeEvents } = get();
        await unsubscribeRealtimeEvents();
        set({ realtimeConnected: false });
      } catch (error) {
        console.error('Failed to stop realtime monitor:', error);
        throw error;
      }
    },

    subscribeRealtimeEvents: async () => {
      try {
        const subscriptionId = await ComfyUIV2Service.subscribeRealtimeEvents(
          undefined,
          (event: RealtimeEvent) => {
            const { addRealtimeEvent } = get();
            addRealtimeEvent(event);
            
            // 根据事件类型更新相应的状态
            if (event.event_type === 'execution_progress') {
              const data = event.data as ExecutionProgressEvent;
              set(state => ({
                executions: state.executions.map(e => 
                  e.prompt_id === data.prompt_id 
                    ? { ...e, progress: data.percentage, status: 'running' as const }
                    : e
                )
              }));
            } else if (event.event_type === 'execution_completed') {
              const data = event.data as ExecutionCompletedEvent;
              set(state => ({
                executions: state.executions.map(e => 
                  e.prompt_id === data.prompt_id 
                    ? { 
                        ...e, 
                        status: 'completed' as const, 
                        results: data.outputs,
                        output_urls: data.output_urls,
                        execution_time: data.execution_time
                      }
                    : e
                )
              }));
            } else if (event.event_type === 'execution_failed') {
              const data = event.data;
              set(state => ({
                executions: state.executions.map(e => 
                  e.prompt_id === data.prompt_id 
                    ? { ...e, status: 'failed' as const, error_message: data.error }
                    : e
                )
              }));
            }
          }
        );
        
        set({ realtimeSubscriptionId: subscriptionId });
      } catch (error) {
        console.error('Failed to subscribe to realtime events:', error);
        throw error;
      }
    },

    unsubscribeRealtimeEvents: async () => {
      const { realtimeSubscriptionId } = get();
      if (realtimeSubscriptionId) {
        try {
          await ComfyUIV2Service.unsubscribeRealtimeEvents(realtimeSubscriptionId);
          set({ realtimeSubscriptionId: null });
        } catch (error) {
          console.error('Failed to unsubscribe from realtime events:', error);
        }
      }
    },

    addRealtimeEvent: (event: RealtimeEvent) => {
      set(state => ({
        realtimeEvents: [event, ...state.realtimeEvents].slice(0, 1000) // 保留最近1000个事件
      }));
    },

    clearRealtimeEvents: () => {
      set({ realtimeEvents: [] });
    },

    // ==================== 选择管理 ====================
    
    selectWorkflow: (id: string) => {
      set(state => ({
        selectedWorkflowIds: [...new Set([...state.selectedWorkflowIds, id])]
      }));
    },

    deselectWorkflow: (id: string) => {
      set(state => ({
        selectedWorkflowIds: state.selectedWorkflowIds.filter(wId => wId !== id)
      }));
    },

    selectAllWorkflows: () => {
      set(state => ({
        selectedWorkflowIds: state.workflows.map(w => w.id)
      }));
    },

    clearWorkflowSelection: () => {
      set({ selectedWorkflowIds: [] });
    },

    selectTemplate: (id: string) => {
      set(state => ({
        selectedTemplateIds: [...new Set([...state.selectedTemplateIds, id])]
      }));
    },

    deselectTemplate: (id: string) => {
      set(state => ({
        selectedTemplateIds: state.selectedTemplateIds.filter(tId => tId !== id)
      }));
    },

    selectAllTemplates: () => {
      set(state => ({
        selectedTemplateIds: state.templates.map(t => t.id)
      }));
    },

    clearTemplateSelection: () => {
      set({ selectedTemplateIds: [] });
    },

    selectExecution: (id: string) => {
      set(state => ({
        selectedExecutionIds: [...new Set([...state.selectedExecutionIds, id])]
      }));
    },

    deselectExecution: (id: string) => {
      set(state => ({
        selectedExecutionIds: state.selectedExecutionIds.filter(eId => eId !== id)
      }));
    },

    clearExecutionSelection: () => {
      set({ selectedExecutionIds: [] });
    },

    // ==================== 重置和清理 ====================
    
    reset: () => {
      set(initialState);
    },

    cleanup: () => {
      const { unsubscribeRealtimeEvents } = get();
      unsubscribeRealtimeEvents();
      ComfyUIV2Service.cleanup();
      set(initialState);
    },
  }))
);

// ==================== 选择器 Hooks ====================

/**
 * 获取过滤后的工作流
 */
export const useFilteredWorkflows = () => {
  return useComfyUIV2Store(state => {
    let filtered = state.workflows;
    
    if (state.workflowFilters.category) {
      filtered = filtered.filter(w => w.category === state.workflowFilters.category);
    }
    
    if (state.workflowFilters.tags && state.workflowFilters.tags.length > 0) {
      filtered = filtered.filter(w => 
        state.workflowFilters.tags!.some(tag => w.tags.includes(tag))
      );
    }
    
    if (state.workflowFilters.searchQuery) {
      const query = state.workflowFilters.searchQuery.toLowerCase();
      filtered = filtered.filter(w => 
        w.name.toLowerCase().includes(query) ||
        w.description?.toLowerCase().includes(query)
      );
    }
    
    return filtered;
  });
};

/**
 * 获取过滤后的模板
 */
export const useFilteredTemplates = () => {
  return useComfyUIV2Store(state => {
    let filtered = state.templates;
    
    if (state.templateFilters.category) {
      filtered = filtered.filter(t => t.category === state.templateFilters.category);
    }
    
    if (state.templateFilters.tags && state.templateFilters.tags.length > 0) {
      filtered = filtered.filter(t => 
        state.templateFilters.tags!.some(tag => t.tags.includes(tag))
      );
    }
    
    if (state.templateFilters.searchQuery) {
      const query = state.templateFilters.searchQuery.toLowerCase();
      filtered = filtered.filter(t => 
        t.name.toLowerCase().includes(query) ||
        t.description?.toLowerCase().includes(query)
      );
    }
    
    return filtered;
  });
};

/**
 * 获取过滤后的执行记录
 */
export const useFilteredExecutions = () => {
  return useComfyUIV2Store(state => {
    let filtered = state.executions;
    
    if (state.executionFilters.status) {
      filtered = filtered.filter(e => e.status === state.executionFilters.status);
    }
    
    if (state.executionFilters.workflowId) {
      filtered = filtered.filter(e => e.workflow_id === state.executionFilters.workflowId);
    }
    
    if (state.executionFilters.templateId) {
      filtered = filtered.filter(e => e.template_id === state.executionFilters.templateId);
    }
    
    return filtered;
  });
};
