import { create } from 'zustand';
import { invoke } from '@tauri-apps/api/core';
import {
  ProjectBatchClassificationRequest,
  ProjectBatchClassificationResponse
} from '../types/videoClassification';

// 类型定义
export interface VideoClassificationRecord {
  id: string;
  segment_id: string;
  material_id: string;
  project_id: string;
  category: string;
  confidence: number;
  reasoning: string;
  features: string[];
  product_match: boolean;
  quality_score: number;
  gemini_file_uri?: string;
  raw_response?: string;
  status: 'Classified' | 'Failed' | 'NeedsReview';
  error_message?: string;
  created_at: string;
  updated_at: string;
}

export interface BatchClassificationRequest {
  material_id: string;
  project_id: string;
  overwrite_existing: boolean;
  priority?: number;
}

export interface QueueStats {
  status: 'Stopped' | 'Running' | 'Paused';
  total_tasks: number;
  pending_tasks: number;
  processing_tasks: number;
  completed_tasks: number;
  failed_tasks: number;
  current_task_id?: string;
  processing_rate: number;
}

export interface TaskProgress {
  task_id: string;
  status: 'Pending' | 'Uploading' | 'Analyzing' | 'Completed' | 'Failed' | 'Cancelled';
  progress_percentage: number;
  current_step: string;
  error_message?: string;
  started_at?: string;
  estimated_completion?: string;
}

export interface ClassificationStats {
  total_tasks: number;
  pending_tasks: number;
  processing_tasks: number;
  completed_tasks: number;
  failed_tasks: number;
  total_classifications: number;
  successful_classifications: number;
  failed_classifications: number;
  needs_review_classifications: number;
  average_confidence: number;
  average_quality_score: number;
}

interface VideoClassificationState {
  // 状态
  isLoading: boolean;
  error: string | null;
  queueStats: QueueStats | null;
  taskProgress: Record<string, TaskProgress>;
  classificationRecords: Record<string, VideoClassificationRecord[]>; // material_id -> records
  
  // Actions
  startClassification: (request: BatchClassificationRequest) => Promise<string[]>;
  startProjectBatchClassification: (request: ProjectBatchClassificationRequest) => Promise<ProjectBatchClassificationResponse>;
  getQueueStatus: () => Promise<QueueStats>;
  getProjectQueueStatus: (projectId: string) => Promise<QueueStats>;
  getTaskProgress: (taskId: string) => Promise<TaskProgress | null>;
  getAllTaskProgress: () => Promise<Record<string, TaskProgress>>;
  getProjectTaskProgress: (projectId: string) => Promise<Record<string, TaskProgress>>;
  stopQueue: () => Promise<void>;
  pauseQueue: () => Promise<void>;
  resumeQueue: () => Promise<void>;
  getMaterialClassifications: (materialId: string) => Promise<VideoClassificationRecord[]>;
  getClassificationStats: (projectId?: string) => Promise<ClassificationStats>;
  isSegmentClassified: (segmentId: string) => Promise<boolean>;
  cancelTask: (taskId: string) => Promise<void>;
  retryTask: (taskId: string) => Promise<void>;
  testGeminiConnection: () => Promise<string>;
  
  // UI helpers
  clearError: () => void;
  refreshQueueStatus: () => Promise<QueueStats | null>;
  refreshTaskProgress: () => Promise<void>;
}

export const useVideoClassificationStore = create<VideoClassificationState>((set, get) => ({
  // 初始状态
  isLoading: false,
  error: null,
  queueStats: null,
  taskProgress: {},
  classificationRecords: {},

  // Actions
  startClassification: async (request: BatchClassificationRequest) => {
    set({ isLoading: true, error: null });
    try {
      const taskIds = await invoke<string[]>('start_video_classification', { request });
      
      // 刷新队列状态
      await get().refreshQueueStatus();
      await get().refreshTaskProgress();
      
      set({ isLoading: false });
      return taskIds;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '启动分类失败';
      set({ error: errorMessage, isLoading: false });
      throw new Error(errorMessage);
    }
  },

  startProjectBatchClassification: async (request: ProjectBatchClassificationRequest) => {
    set({ isLoading: true, error: null });
    try {
      const response = await invoke<ProjectBatchClassificationResponse>('start_project_batch_classification', { request });

      // 刷新队列状态
      await get().refreshQueueStatus();
      await get().refreshTaskProgress();

      set({ isLoading: false });
      return response;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '启动项目一键分类失败';
      set({ error: errorMessage, isLoading: false });
      throw new Error(errorMessage);
    }
  },

  getQueueStatus: async () => {
    try {
      const stats = await invoke<QueueStats>('get_classification_queue_status');
      set({ queueStats: stats });
      return stats;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '获取队列状态失败';
      set({ error: errorMessage });
      throw new Error(errorMessage);
    }
  },

  getProjectQueueStatus: async (projectId: string) => {
    try {
      const stats = await invoke<QueueStats>('get_project_classification_queue_status', { projectId });
      set({ queueStats: stats });
      return stats;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '获取项目队列状态失败';
      set({ error: errorMessage });
      throw new Error(errorMessage);
    }
  },

  getTaskProgress: async (taskId: string) => {
    try {
      const progress = await invoke<TaskProgress | null>('get_classification_task_progress', { taskId });
      if (progress) {
        set(state => ({
          taskProgress: { ...state.taskProgress, [taskId]: progress }
        }));
      }
      return progress;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '获取任务进度失败';
      set({ error: errorMessage });
      throw new Error(errorMessage);
    }
  },

  getAllTaskProgress: async () => {
    try {
      const allProgress = await invoke<Record<string, TaskProgress>>('get_all_classification_task_progress');
      set({ taskProgress: allProgress });
      return allProgress;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '获取所有任务进度失败';
      set({ error: errorMessage });
      throw new Error(errorMessage);
    }
  },

  getProjectTaskProgress: async (projectId: string) => {
    try {
      const projectProgress = await invoke<Record<string, TaskProgress>>('get_project_classification_task_progress', { projectId });
      set({ taskProgress: projectProgress });
      return projectProgress;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '获取项目任务进度失败';
      set({ error: errorMessage });
      throw new Error(errorMessage);
    }
  },

  stopQueue: async () => {
    set({ isLoading: true, error: null });
    try {
      console.log('🛑 调用停止队列命令...');
      await invoke('stop_classification_queue');
      console.log('✅ 停止队列命令执行成功，刷新状态...');

      // 等待一小段时间确保后端状态已更新
      await new Promise(resolve => setTimeout(resolve, 500));

      // 刷新队列状态
      const newStats = await get().getQueueStatus();
      console.log('📊 刷新后的队列状态:', newStats);

      set({ isLoading: false });
    } catch (error) {
      console.error('❌ 停止队列失败:', error);
      const errorMessage = typeof error === 'string' ? error : '停止队列失败';
      set({ error: errorMessage, isLoading: false });
      throw new Error(errorMessage);
    }
  },

  pauseQueue: async () => {
    set({ isLoading: true, error: null });
    try {
      console.log('⏸️ 调用暂停队列命令...');
      await invoke('pause_classification_queue');
      console.log('✅ 暂停队列命令执行成功，刷新状态...');

      // 等待一小段时间确保后端状态已更新
      await new Promise(resolve => setTimeout(resolve, 500));

      // 刷新队列状态
      const newStats = await get().getQueueStatus();
      console.log('📊 刷新后的队列状态:', newStats);

      set({ isLoading: false });
    } catch (error) {
      console.error('❌ 暂停队列失败:', error);
      const errorMessage = typeof error === 'string' ? error : '暂停队列失败';
      set({ error: errorMessage, isLoading: false });
      throw new Error(errorMessage);
    }
  },

  resumeQueue: async () => {
    set({ isLoading: true, error: null });
    try {
      console.log('▶️ 调用恢复队列命令...');
      await invoke('resume_classification_queue');
      console.log('✅ 恢复队列命令执行成功，刷新状态...');

      // 等待一小段时间确保后端状态已更新
      await new Promise(resolve => setTimeout(resolve, 500));

      // 刷新队列状态
      const newStats = await get().getQueueStatus();
      console.log('📊 刷新后的队列状态:', newStats);

      set({ isLoading: false });
    } catch (error) {
      console.error('❌ 恢复队列失败:', error);
      const errorMessage = typeof error === 'string' ? error : '恢复队列失败';
      set({ error: errorMessage, isLoading: false });
      throw new Error(errorMessage);
    }
  },

  getMaterialClassifications: async (materialId: string) => {
    try {
      const records = await invoke<VideoClassificationRecord[]>('get_material_classification_records', { materialId });
      set(state => ({
        classificationRecords: { ...state.classificationRecords, [materialId]: records }
      }));
      return records;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '获取分类记录失败';
      set({ error: errorMessage });
      throw new Error(errorMessage);
    }
  },

  getClassificationStats: async (projectId?: string) => {
    try {
      const stats = await invoke<ClassificationStats>('get_classification_statistics', { projectId });
      return stats;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '获取分类统计失败';
      set({ error: errorMessage });
      throw new Error(errorMessage);
    }
  },

  isSegmentClassified: async (segmentId: string) => {
    try {
      const isClassified = await invoke<boolean>('is_segment_classified', { segmentId });
      return isClassified;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '检查分类状态失败';
      set({ error: errorMessage });
      throw new Error(errorMessage);
    }
  },

  cancelTask: async (taskId: string) => {
    set({ isLoading: true, error: null });
    try {
      await invoke('cancel_classification_task', { taskId });
      await get().refreshTaskProgress();
      set({ isLoading: false });
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '取消任务失败';
      set({ error: errorMessage, isLoading: false });
      throw new Error(errorMessage);
    }
  },

  retryTask: async (taskId: string) => {
    set({ isLoading: true, error: null });
    try {
      await invoke('retry_classification_task', { taskId });
      await get().refreshTaskProgress();
      set({ isLoading: false });
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : '重试任务失败';
      set({ error: errorMessage, isLoading: false });
      throw new Error(errorMessage);
    }
  },

  testGeminiConnection: async () => {
    set({ isLoading: true, error: null });
    try {
      const result = await invoke<string>('test_gemini_connection');
      set({ isLoading: false });
      return result;
    } catch (error) {
      const errorMessage = typeof error === 'string' ? error : 'Gemini连接测试失败';
      set({ error: errorMessage, isLoading: false });
      throw new Error(errorMessage);
    }
  },

  // UI helpers
  clearError: () => set({ error: null }),

  refreshQueueStatus: async () => {
    try {
      const stats = await get().getQueueStatus();
      return stats;
    } catch (error) {
      // 静默处理错误，避免重复设置错误状态
      console.error('刷新队列状态失败:', error);
      return null;
    }
  },

  refreshTaskProgress: async () => {
    try {
      await get().getAllTaskProgress();
    } catch (error) {
      // 静默处理错误，避免重复设置错误状态
      console.error('刷新任务进度失败:', error);
    }
  },
}));
