import { useCallback } from "react";

export default function useAppLoaders({
  selectedTaskId,
  setTasks,
  setSelectedTaskId,
  setAccountAssignments,
  setTaskStatusMap,
  setSettings,
  setAccounts,
  setAccountEvents,
  setAccountStats,
  setGlobalStatus
}) {
  const loadTasks = useCallback(async () => {
    const tasksData = await window.api.listTasks();
    setTasks(tasksData);
    if (!tasksData.length) {
      setSelectedTaskId(null);
      return tasksData;
    }
    if (selectedTaskId == null) {
      setSelectedTaskId(tasksData[0].id);
      return tasksData;
    }
    if (!tasksData.some((task) => task.id === selectedTaskId)) {
      setSelectedTaskId(tasksData[0].id);
    }
    return tasksData;
  }, [selectedTaskId, setSelectedTaskId, setTasks]);

  const loadAccountAssignments = useCallback(async () => {
    if (!window.api) return;
    const assignments = await window.api.listAccountAssignments();
    setAccountAssignments(assignments || []);
  }, [setAccountAssignments]);

  const loadTaskStatuses = useCallback(async (tasksData) => {
    const entries = await Promise.all(
      (tasksData || []).map(async (task) => {
        const status = await window.api.taskStatus(task.id);
        return [task.id, status];
      })
    );
    const map = {};
    entries.forEach(([id, status]) => {
      map[id] = status;
    });
    setTaskStatusMap(map);
  }, [setTaskStatusMap]);

  const loadBase = useCallback(async () => {
    if (!window.api) return;
    const [settingsData, accountsData, eventsData, statusData] = await Promise.all([
      window.api.getSettings(),
      window.api.listAccounts(),
      window.api.listAccountEvents(200),
      window.api.getStatus()
    ]);
    setSettings(settingsData);
    setAccounts(accountsData);
    setAccountEvents(eventsData);
    setAccountStats(statusData.accountStats || []);
    setGlobalStatus({
      connectedSessions: statusData.connectedSessions || 0,
      totalAccounts: statusData.totalAccounts || 0
    });
    const tasksData = await loadTasks();
    await loadAccountAssignments();
    await loadTaskStatuses(tasksData);
  }, [
    loadAccountAssignments,
    loadTaskStatuses,
    loadTasks,
    setAccountEvents,
    setAccountStats,
    setAccounts,
    setGlobalStatus,
    setSettings
  ]);

  return {
    loadTasks,
    loadAccountAssignments,
    loadTaskStatuses,
    loadBase
  };
}
