import { useMemo } from "react";

export default function useTaskSelectors({
  tasks,
  taskStatusMap,
  deferredTaskSearch,
  taskFilter,
  taskSort
}) {
  const taskSummary = useMemo(() => {
    const totals = {
      total: tasks.length,
      running: 0,
      queue: 0,
      dailyUsed: 0,
      dailyLimit: 0
    };
    tasks.forEach((task) => {
      const status = taskStatusMap[task.id];
      if (status && status.running) totals.running += 1;
      if (status) {
        totals.queue += Number(status.queueCount || 0);
        totals.dailyUsed += Number(status.dailyUsed || 0);
        totals.dailyLimit += Number(status.dailyLimit || 0);
      }
    });
    return totals;
  }, [tasks, taskStatusMap]);

  const filteredTasks = useMemo(() => {
    const query = deferredTaskSearch.trim().toLowerCase();
    const filtered = tasks.filter((task) => {
      const name = (task.name || "").toLowerCase();
      const group = (task.our_group || "").toLowerCase();
      const matchesQuery = !query || name.includes(query) || group.includes(query) || String(task.id).includes(query);
      if (!matchesQuery) return false;
      const status = taskStatusMap[task.id];
      if (taskFilter === "running") return Boolean(status && status.running);
      if (taskFilter === "stopped") return Boolean(status && !status.running);
      return true;
    });
    const sorted = [...filtered].sort((a, b) => {
      const statusA = taskStatusMap[a.id];
      const statusB = taskStatusMap[b.id];
      if (taskSort === "queue") {
        return (statusB ? statusB.queueCount : 0) - (statusA ? statusA.queueCount : 0);
      }
      if (taskSort === "limit") {
        return (statusB ? statusB.dailyLimit : 0) - (statusA ? statusA.dailyLimit : 0);
      }
      if (taskSort === "lastMessage") {
        const dateA = statusA && statusA.monitorInfo && statusA.monitorInfo.lastMessageAt
          ? Date.parse(statusA.monitorInfo.lastMessageAt) || 0
          : 0;
        const dateB = statusB && statusB.monitorInfo && statusB.monitorInfo.lastMessageAt
          ? Date.parse(statusB.monitorInfo.lastMessageAt) || 0
          : 0;
        return dateB - dateA;
      }
      if (taskSort === "activity") {
        const aActive = statusA && statusA.running ? 1 : 0;
        const bActive = statusB && statusB.running ? 1 : 0;
        if (bActive !== aActive) return bActive - aActive;
      }
      if (taskSort === "id") {
        return b.id - a.id;
      }
      return b.id - a.id;
    });
    return sorted;
  }, [tasks, deferredTaskSearch, taskFilter, taskSort, taskStatusMap]);

  return { taskSummary, filteredTasks };
}
