import React, { createContext, useState, useContext, ReactNode } from 'react';
import { Task } from '../types/task';
import { MOCK_TASKS } from '../data/mockData';

interface TasksContextData {
  tasks: Task[];
  getTaskById: (id: string) => Task | undefined;
  updateTask: (updatedTask: Task) => void;
  runTask: (id: string) => void;
}

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

export const TasksProvider: React.FC<{children: ReactNode}> = ({ children }) => {
  const [tasks, setTasks] = useState<Task[]>(MOCK_TASKS);

  const getTaskById = (id: string) => {
    return tasks.find(task => task.id === id);
  };

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

  const runTask = (id: string) => {
    setTasks(prevTasks =>
      prevTasks.map(task =>
        task.id === id ? { ...task, status: 'RUNNING' } : task
      )
    );
    // 模拟任务完成
    setTimeout(() => {
        setTasks(prevTasks =>
            prevTasks.map(task =>
              task.id === id ? { ...task, status: 'COMPLETED' } : task
            )
          );
    }, 5000);
  };

  return (
    <TasksContext.Provider value={{ tasks, getTaskById, updateTask, runTask }}>
      {children}
    </TasksContext.Provider>
  );
};

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