import { emptyTaskForm, normalizeTask, sanitizeTaskForm } from "../appDefaults.js";

export default function useTaskLoaders({
  taskAutosaveReady,
  setTaskForm,
  setCompetitorText,
  setSelectedAccountIds,
  setTaskAccountRoles,
  setLogs,
  setInvites,
  setFallbackList,
  setConfirmQueue,
  setGroupVisibility,
  setTaskStatus,
  setMembershipStatus,
  showNotification,
  selectedTaskId
}) {
  async function loadSelectedTask(taskId) {
    taskAutosaveReady.current = false;
    if (!taskId) {
      setTaskForm(emptyTaskForm);
      setCompetitorText("");
      setSelectedAccountIds([]);
      setTaskAccountRoles({});
      setLogs([]);
      setInvites([]);
      setGroupVisibility([]);
      setConfirmQueue([]);
      setTaskStatus({
        running: false,
        queueCount: 0,
        dailyRemaining: 0,
        dailyUsed: 0,
        dailyLimit: 0,
        monitorInfo: { monitoring: false, accountId: 0, accountIds: [], groups: [], lastMessageAt: "", lastSource: "" },
        nextRunAt: "",
        nextInviteAccountId: 0,
        lastInviteAccountId: 0,
        pendingStats: { total: 0, withUsername: 0, withAccessHash: 0, withoutData: 0 }
      });
      taskAutosaveReady.current = true;
      return;
    }
    const details = await window.api.getTask(taskId);
    if (!details) {
      taskAutosaveReady.current = true;
      return;
    }
    setTaskForm(sanitizeTaskForm({ ...emptyTaskForm, ...normalizeTask(details.task) }));
    setCompetitorText((details.competitors || []).join("\n"));
    const roleMap = {};
    if (details.accountRoles && details.accountRoles.length) {
      details.accountRoles.forEach((item) => {
        const roleConfirm = item.roleConfirm != null ? item.roleConfirm : item.roleInvite;
        roleMap[item.accountId] = {
          monitor: Boolean(item.roleMonitor),
          invite: Boolean(item.roleInvite),
          confirm: Boolean(roleConfirm),
          inviteLimit: Number(item.inviteLimit || 0)
        };
      });
    } else {
      (details.accountIds || []).forEach((accountId) => {
        roleMap[accountId] = { monitor: true, invite: true, confirm: true, inviteLimit: 1 };
      });
    }
    setTaskAccountRoles(roleMap);
    setSelectedAccountIds(Object.keys(roleMap).map((id) => Number(id)));
    setLogs(await window.api.listLogs({ limit: 100, taskId }));
    setInvites(await window.api.listInvites({ limit: 200, taskId }));
    setFallbackList(await window.api.listFallback({ limit: 500, taskId }));
    setConfirmQueue(await window.api.listConfirmQueue({ limit: 500, taskId }));
    setGroupVisibility([]);
    setTaskStatus(await window.api.taskStatus(taskId));
    taskAutosaveReady.current = true;
  }

  async function refreshMembership(source = "manual", showToast = false) {
    if (!window.api) {
      showNotification("Electron API недоступен. Откройте приложение в Electron.", "error");
      return;
    }
    try {
      const payload = selectedTaskId != null
        ? await window.api.membershipStatusByTask(selectedTaskId)
        : await window.api.getMembershipStatus();
      if (payload && payload.ok === false) {
        showNotification(payload.error || "Не удалось проверить участие.", "error");
        return;
      }
      const map = {};
      (payload || []).forEach((item) => {
        if (item && item.accountId != null) {
          map[item.accountId] = item;
        }
      });
      setMembershipStatus(map);
      if (showToast) {
        showNotification("Проверка участия завершена.", "success");
      }
    } catch (error) {
      showNotification(error.message || String(error), "error");
    }
  }

  return { loadSelectedTask, refreshMembership };
}
