import React, {
  createContext,
  useState,
  useContext,
  ReactNode,
  useEffect,
  useMemo,
  useCallback,
} from 'react';
import { Task } from '../types/task';
import { AppConfig } from '../types/config';
import { getConfig } from '../services/configService';
import {
  getTasks as getTasksService,
  getTaskDetail as getTaskDetailService,
} from '../services/taskService';

interface TasksContextData {
  tasks: Task[];
  serverUrl: string | null;
  getTaskById: (id: string) => Task | undefined;
  updateTask: (updatedTask: Task) => void;
  refreshConfig: () => Promise<void>;
  isConfigLoaded: boolean;
  fetchTaskDetail: (taskId: string) => Promise<void>;
  refreshTasks: () => Promise<void>;
}

const TasksContext = createContext<TasksContextData>({} as TasksContextData);

export const TasksProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [isConfigLoaded, setIsConfigLoaded] = useState(false);
  const [serverUrl, setServerUrl] = useState<string | null>(null);

  const refreshTasks = useCallback(async () => {
    if (!isConfigLoaded) return;
    try {
      const fetchedTasks = await getTasksService({ pageNum: 1, pageSize: 100 });
      setTasks(fetchedTasks);
    } catch (error) {
      console.error('获取任务列表失败 (context):', error);
      setTasks([]);
    }
  }, [isConfigLoaded]);

  useEffect(() => {
    const loadApp = async () => {
      try {
        const config = await getConfig();
        if (config) {
          applyConfig(config);
          setIsConfigLoaded(true);
        } else {
          console.log('没有找到配置文件，使用空数据');
          setIsConfigLoaded(false);
        }
      } catch (error) {
        console.error('加载配置失败:', error);
        setIsConfigLoaded(false);
      }
    };

    loadApp();
  }, []);

  useEffect(() => {
    if (isConfigLoaded) {
      refreshTasks();
    }
  }, [isConfigLoaded, refreshTasks]);

  const applyConfig = (config: AppConfig) => {
    if (config.serverUrl) {
      setServerUrl(config.serverUrl);
    }
  };

  const refreshConfig = useCallback(async () => {
    try {
      const config = await getConfig();
      if (config) {
        applyConfig(config);
        setIsConfigLoaded(true); // 确保配置加载后再次触发任务获取
      } else {
        console.log('刷新配置时没有找到配置文件');
        setIsConfigLoaded(false);
      }
    } catch (error) {
      console.error('刷新配置失败:', error);
      setIsConfigLoaded(false);
    }
  }, []);

  const getTaskById = useCallback(
    (id: string) => {
      const task = tasks.find(t => t.id === id);
      return task;
    },
    [tasks],
  );

  const fetchTaskDetail = useCallback(async (taskId: string) => {
    try {
      const taskDetail = await getTaskDetailService(taskId);
      setTasks(prevTasks =>
        prevTasks.map(task =>
          task.id === taskId ? { ...task, detail: taskDetail.detail } : task,
        ),
      );
    } catch (error) {
      console.error('获取任务详情失败 (context):', error);
    }
  }, []);

  const updateTask = useCallback((updatedTask: Task) => {
    setTasks(prevTasks =>
      prevTasks.map(task => (task.id === updatedTask.id ? updatedTask : task)),
    );
  }, []);

  const contextValue = useMemo(
    () => ({
      tasks,
      serverUrl,
      getTaskById,
      updateTask,
      refreshConfig,
      isConfigLoaded,
      fetchTaskDetail,
      refreshTasks,
    }),
    [
      tasks,
      serverUrl,
      getTaskById,
      updateTask,
      refreshConfig,
      isConfigLoaded,
      fetchTaskDetail,
      refreshTasks,
    ],
  );

  return (
    <TasksContext.Provider value={contextValue}>
      {children}
    </TasksContext.Provider>
  );
};

export function useTasks() {
  return useContext(TasksContext);
}
