import { useState, useEffect, useCallback } from 'react';
import type { TvaiTask, TvaiTaskStatus } from '../types/tvai';
import { tvaiService, addTvaiEventListener, removeTvaiEventListener } from '../services/tvaiService';

export interface UseTvaiOptions {
  autoRefresh?: boolean;
  refreshInterval?: number;
}

export interface UseTvaiReturn {
  tasks: TvaiTask[];
  isLoading: boolean;
  error: string | null;
  refreshTasks: () => Promise<void>;
  getTaskById: (taskId: string) => TvaiTask | undefined;
  cancelTask: (taskId: string) => Promise<void>;
  cleanupCompletedTasks: () => Promise<number>;
  getTasksByStatus: (status: TvaiTaskStatus) => TvaiTask[];
  getRunningTasksCount: () => number;
  getCompletedTasksCount: () => number;
  getFailedTasksCount: () => number;
}

/**
 * TVAI 任务管理 Hook
 */
export function useTvai(options: UseTvaiOptions = {}): UseTvaiReturn {
  const { autoRefresh = true, refreshInterval = 10000 } = options; // 增加轮询间隔，主要依赖事件推送
  
  const [tasks, setTasks] = useState<TvaiTask[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 刷新任务列表
  const refreshTasks = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);
      const allTasks = await tvaiService.getAllTvaiTasks();
      setTasks(allTasks);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch tasks');
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 根据ID获取任务
  const getTaskById = useCallback((taskId: string): TvaiTask | undefined => {
    return tasks.find(task => task.id === taskId);
  }, [tasks]);

  // 取消任务
  const cancelTask = useCallback(async (taskId: string): Promise<void> => {
    try {
      await tvaiService.cancelTvaiTask(taskId);
      await refreshTasks();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to cancel task');
      throw err;
    }
  }, [refreshTasks]);

  // 清理已完成的任务
  const cleanupCompletedTasks = useCallback(async (): Promise<number> => {
    try {
      const removedCount = await tvaiService.cleanupCompletedTvaiTasks();
      await refreshTasks();
      return removedCount;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to cleanup tasks');
      throw err;
    }
  }, [refreshTasks]);

  // 根据状态获取任务
  const getTasksByStatus = useCallback((status: TvaiTaskStatus): TvaiTask[] => {
    return tasks.filter(task => task.status === status);
  }, [tasks]);

  // 获取运行中的任务数量
  const getRunningTasksCount = useCallback((): number => {
    return tasks.filter(task => 
      task.status === 'Pending' || task.status === 'Processing'
    ).length;
  }, [tasks]);

  // 获取已完成的任务数量
  const getCompletedTasksCount = useCallback((): number => {
    return tasks.filter(task => task.status === 'Completed').length;
  }, [tasks]);

  // 获取失败的任务数量
  const getFailedTasksCount = useCallback((): number => {
    return tasks.filter(task => task.status === 'Failed').length;
  }, [tasks]);

  // 处理任务事件 - 实时推送机制
  useEffect(() => {
    const handleTaskCreated = async (taskId: string) => {
      console.log('Task created (real-time):', taskId);
      // 立即刷新任务列表以获取新任务
      await refreshTasks();
    };

    const handleTaskUpdated = async (taskId: string) => {
      console.log('Task updated (real-time):', taskId);
      // 获取单个任务的最新状态并更新
      try {
        const updatedTask = await tvaiService.getTvaiTaskStatus(taskId);
        if (updatedTask) {
          setTasks(prevTasks => {
            const taskIndex = prevTasks.findIndex(task => task.id === taskId);
            if (taskIndex >= 0) {
              // 更新现有任务
              const newTasks = [...prevTasks];
              newTasks[taskIndex] = updatedTask;
              return newTasks;
            } else {
              // 添加新任务（如果不存在）
              return [...prevTasks, updatedTask];
            }
          });
        }
      } catch (error) {
        console.error('Failed to update task:', error);
        // 如果单个任务更新失败，回退到全量刷新
        await refreshTasks();
      }
    };

    // 添加事件监听器
    addTvaiEventListener('tvai_task_created', handleTaskCreated);
    addTvaiEventListener('tvai_task_updated', handleTaskUpdated);

    // 清理函数
    return () => {
      removeTvaiEventListener('tvai_task_created', handleTaskCreated);
      removeTvaiEventListener('tvai_task_updated', handleTaskUpdated);
    };
  }, [refreshTasks]);

  // 智能轮询 - 只在有运行中的任务时才轮询
  useEffect(() => {
    if (!autoRefresh) return;

    const hasRunningTasks = tasks.some(task =>
      task.status === 'Pending' || task.status === 'Processing'
    );

    if (!hasRunningTasks) return; // 没有运行中的任务时不进行轮询

    const interval = setInterval(() => {
      console.log('Polling for task updates (fallback mechanism)');
      refreshTasks();
    }, refreshInterval);

    return () => clearInterval(interval);
  }, [autoRefresh, refreshInterval, refreshTasks, tasks]);

  // 初始加载
  useEffect(() => {
    refreshTasks();
  }, [refreshTasks]);

  return {
    tasks,
    isLoading,
    error,
    refreshTasks,
    getTaskById,
    cancelTask,
    cleanupCompletedTasks,
    getTasksByStatus,
    getRunningTasksCount,
    getCompletedTasksCount,
    getFailedTasksCount,
  };
}

/**
 * 单个任务状态管理 Hook
 */
export function useTvaiTask(taskId: string) {
  const [task, setTask] = useState<TvaiTask | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const refreshTask = useCallback(async () => {
    if (!taskId) return;
    
    try {
      setIsLoading(true);
      setError(null);
      const taskData = await tvaiService.getTvaiTaskStatus(taskId);
      setTask(taskData);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch task');
    } finally {
      setIsLoading(false);
    }
  }, [taskId]);

  const cancelTask = useCallback(async (): Promise<void> => {
    if (!taskId) return;
    
    try {
      await tvaiService.cancelTvaiTask(taskId);
      await refreshTask();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to cancel task');
      throw err;
    }
  }, [taskId, refreshTask]);

  // 监听任务更新事件
  useEffect(() => {
    const handleTaskUpdated = (updatedTaskId: string) => {
      if (updatedTaskId === taskId) {
        refreshTask();
      }
    };

    addTvaiEventListener('tvai_task_updated', handleTaskUpdated);

    return () => {
      removeTvaiEventListener('tvai_task_updated', handleTaskUpdated);
    };
  }, [taskId, refreshTask]);

  // 初始加载
  useEffect(() => {
    refreshTask();
  }, [refreshTask]);

  return {
    task,
    isLoading,
    error,
    refreshTask,
    cancelTask,
    isCompleted: task?.status === 'Completed',
    isFailed: task?.status === 'Failed',
    isRunning: task?.status === 'Processing',
    isPending: task?.status === 'Pending',
    isCancelled: task?.status === 'Cancelled',
  };
}

/**
 * TVAI 系统信息 Hook
 */
export function useTvaiSystemInfo() {
  const [systemInfo, setSystemInfo] = useState({
    topazPath: null as string | null,
    gpuInfo: null as any,
    ffmpegInfo: null as any,
    isInitialized: false,
  });
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const detectSystem = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);
      
      const [topazPath, gpuInfo, ffmpegInfo] = await Promise.all([
        tvaiService.detectTopazInstallation(),
        tvaiService.detectGpuSupport(),
        tvaiService.detectFfmpeg(),
      ]);

      setSystemInfo({
        topazPath,
        gpuInfo,
        ffmpegInfo,
        isInitialized: !!topazPath,
      });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to detect system');
    } finally {
      setIsLoading(false);
    }
  }, []);

  const initializeTvai = useCallback(async (config: {
    topaz_path?: string;
    use_gpu?: boolean;
    temp_dir?: string;
  }) => {
    try {
      setIsLoading(true);
      setError(null);
      
      await tvaiService.initializeTvaiConfig(config);
      await detectSystem(); // 重新检测系统状态
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to initialize TVAI');
      throw err;
    } finally {
      setIsLoading(false);
    }
  }, [detectSystem]);

  // 初始检测
  useEffect(() => {
    detectSystem();
  }, [detectSystem]);

  return {
    systemInfo,
    isLoading,
    error,
    detectSystem,
    initializeTvai,
  };
}
