"use client";

/**
 * Background Task Store
 * ─────────────────────
 * React context that tracks long-running background tasks across the app.
 * Tasks survive page navigation — the sidebar shows a spinner and toasts
 * appear when tasks complete.
 */

import { createContext, useCallback, useContext, useMemo, useState } from "react";

export interface BackgroundTask {
  id: string;
  type: string;
  label: string;
  brandId: string;
  status: "running" | "completed" | "failed";
  startedAt: Date;
  completedAt?: Date;
  resultUrl?: string;
  resultSummary?: string;
  error?: string;
  dismissed?: boolean;
}

export interface TaskStore {
  tasks: BackgroundTask[];
  addTask: (task: Pick<BackgroundTask, "id" | "type" | "label" | "brandId" | "resultUrl">) => string;
  completeTask: (id: string, result: { resultUrl: string; resultSummary: string }) => void;
  failTask: (id: string, error: string) => void;
  dismissTask: (id: string) => void;
  clearHistory: () => void;
  runningTasks: BackgroundTask[];
  completedTasks: BackgroundTask[];
  failedTasks: BackgroundTask[];
  recentTasks: BackgroundTask[];
}

const TaskContext = createContext<TaskStore>({
  tasks: [],
  addTask: () => "",
  completeTask: () => {},
  failTask: () => {},
  dismissTask: () => {},
  clearHistory: () => {},
  runningTasks: [],
  completedTasks: [],
  failedTasks: [],
  recentTasks: [],
});

export function TaskProvider({ children }: { children: React.ReactNode }) {
  const [tasks, setTasks] = useState<BackgroundTask[]>([]);

  const addTask = useCallback((t: Pick<BackgroundTask, "id" | "type" | "label" | "brandId" | "resultUrl">) => {
    const task: BackgroundTask = { ...t, status: "running", startedAt: new Date() };
    setTasks((prev) => [task, ...prev]);
    return t.id;
  }, []);

  const completeTask = useCallback((id: string, result: { resultUrl: string; resultSummary: string }) => {
    setTasks((prev) => prev.map((t) =>
      t.id === id ? { ...t, status: "completed" as const, completedAt: new Date(), resultUrl: result.resultUrl, resultSummary: result.resultSummary } : t
    ));
  }, []);

  const failTask = useCallback((id: string, error: string) => {
    setTasks((prev) => prev.map((t) =>
      t.id === id ? { ...t, status: "failed" as const, completedAt: new Date(), error } : t
    ));
  }, []);

  const dismissTask = useCallback((id: string) => {
    setTasks((prev) => prev.map((t) =>
      t.id === id ? { ...t, dismissed: true } : t
    ));
  }, []);

  const clearHistory = useCallback(() => {
    setTasks((prev) => prev.filter((t) => t.status === "running"));
  }, []);

  const runningTasks = useMemo(() => tasks.filter((t) => t.status === "running"), [tasks]);
  const completedTasks = useMemo(() => tasks.filter((t) => t.status === "completed" && !t.dismissed), [tasks]);
  const failedTasks = useMemo(() => tasks.filter((t) => t.status === "failed" && !t.dismissed), [tasks]);
  const recentTasks = useMemo(() =>
    tasks.filter((t) => t.status !== "running" && !t.dismissed).slice(0, 10),
  [tasks]);

  const value = useMemo<TaskStore>(() => ({
    tasks, addTask, completeTask, failTask, dismissTask, clearHistory,
    runningTasks, completedTasks, failedTasks, recentTasks,
  }), [tasks, addTask, completeTask, failTask, dismissTask, clearHistory, runningTasks, completedTasks, failedTasks, recentTasks]);

  return <TaskContext.Provider value={value}>{children}</TaskContext.Provider>;
}

export function useBackgroundTasks() {
  return useContext(TaskContext);
}
