export default function useAccountManagement({
  selectedTaskId,
  taskAccountRoles,
  setTaskAccountRoles,
  selectedAccountIds,
  setSelectedAccountIds,
  accounts,
  accountBuckets,
  taskForm,
  hasSelectedTask,
  loadAccountAssignments,
  showNotification,
  setTaskNotice,
  setAccounts,
  membershipStatus,
  refreshMembership
}) {
  const persistAccountRoles = async (next) => {
    if (!window.api || selectedTaskId == null) return;
    const rolePayload = Object.entries(next).map(([id, roles]) => ({
      accountId: Number(id),
      roleMonitor: Boolean(roles.monitor),
      roleInvite: Boolean(roles.invite),
      roleConfirm: Boolean(roles.confirm != null ? roles.confirm : roles.invite),
      inviteLimit: Number(roles.inviteLimit || 0)
    }));
    await window.api.appendTaskAccounts({
      taskId: selectedTaskId,
      accountRoles: rolePayload
    });
    await window.api.addAccountEvent({
      accountId: 0,
      phone: "",
      action: "roles_changed",
      details: `задача ${selectedTaskId}: обновлены роли`
    });
    await loadAccountAssignments();
  };

  const updateAccountRole = (accountId, role, value) => {
    const next = { ...taskAccountRoles };
    const existing = next[accountId] || { monitor: false, invite: false, confirm: false, inviteLimit: 0 };
    let inviteLimit = existing.inviteLimit || 0;
    if (role === "invite" && value && inviteLimit === 0) {
      inviteLimit = 1;
    }
    next[accountId] = { ...existing, [role]: value, inviteLimit };
    if (!next[accountId].monitor && !next[accountId].invite && !next[accountId].confirm) {
      delete next[accountId];
    }
    const ids = Object.keys(next).map((id) => Number(id));
    setTaskAccountRoles(next);
    setSelectedAccountIds(ids);
    persistAccountRoles(next);
  };

  const updateAccountInviteLimit = (accountId, value) => {
    const next = { ...taskAccountRoles };
    const existing = next[accountId] || { monitor: false, invite: false, confirm: false, inviteLimit: 0 };
    next[accountId] = { ...existing, inviteLimit: value };
    const ids = Object.keys(next).map((id) => Number(id));
    setTaskAccountRoles(next);
    setSelectedAccountIds(ids);
    persistAccountRoles(next);
  };

  const setAccountRolesAll = (accountId, value) => {
    const next = { ...taskAccountRoles };
    if (value) {
      const existing = next[accountId] || { inviteLimit: 0 };
      next[accountId] = { monitor: true, invite: true, confirm: true, inviteLimit: existing.inviteLimit || 1 };
    } else {
      delete next[accountId];
    }
    const ids = Object.keys(next).map((id) => Number(id));
    setTaskAccountRoles(next);
    setSelectedAccountIds(ids);
    persistAccountRoles(next);
  };

  const applyRolePreset = async (type) => {
    if (!hasSelectedTask) return;
    const availableIds = selectedAccountIds.length
      ? selectedAccountIds
      : accountBuckets.freeOrSelected.map((account) => account.id);
    if (!availableIds.length) {
      showNotification("Нет доступных аккаунтов для назначения.", "error");
      return;
    }
    const next = {};
    if (type === "all") {
      availableIds.forEach((id) => {
        const existing = taskAccountRoles[id] || {};
        next[id] = { monitor: true, invite: true, confirm: true, inviteLimit: existing.inviteLimit || 1 };
      });
    } else if (type === "one") {
      const id = availableIds[0];
      const existing = taskAccountRoles[id] || {};
      next[id] = { monitor: true, invite: true, confirm: true, inviteLimit: existing.inviteLimit || 1 };
    } else if (type === "split") {
      const monitorCount = Math.max(1, Number(taskForm.maxCompetitorBots || 1));
      const inviteCount = Math.max(1, Number(taskForm.maxOurBots || 1));
      const monitorIds = availableIds.slice(0, monitorCount);
      const inviteIds = availableIds.slice(monitorCount, monitorCount + inviteCount);
      const confirmCount = taskForm.separateConfirmRoles ? Math.max(1, Number(taskForm.maxConfirmBots || 1)) : 0;
      const confirmIds = taskForm.separateConfirmRoles
        ? availableIds.slice(monitorCount + inviteCount, monitorCount + inviteCount + confirmCount)
        : [];
      monitorIds.forEach((id) => {
        const existing = taskAccountRoles[id] || {};
        next[id] = { monitor: true, invite: false, confirm: false, inviteLimit: existing.inviteLimit || 0 };
      });
      inviteIds.forEach((id) => {
        const existing = taskAccountRoles[id] || {};
        next[id] = { monitor: false, invite: true, confirm: true, inviteLimit: existing.inviteLimit || 1 };
      });
      confirmIds.forEach((id) => {
        const existing = taskAccountRoles[id] || {};
        next[id] = { monitor: false, invite: false, confirm: true, inviteLimit: existing.inviteLimit || 0 };
      });
      if (monitorIds.length < monitorCount) {
        if (typeof refreshMembership === "function") {
          await refreshMembership("roles");
        }
        const monitorRoleIds = Object.entries(next)
          .filter(([, roles]) => roles && roles.monitor)
          .map(([id]) => Number(id));
        const monitorInCompetitors = monitorRoleIds.filter((id) => {
          const membership = membershipStatus && membershipStatus[id];
          if (!membership) return false;
          const total = Number(membership.competitorTotal || 0);
          return total > 0 && Number(membership.competitorCount || 0) > 0;
        });
        if (!monitorRoleIds.length) {
          showNotification("Нет бота мониторинга. Назначьте роль мониторинга.", "error");
        } else if (!monitorInCompetitors.length) {
          showNotification("Нет бота мониторинга в группах конкурентов. Введите бота в конкурентов или включите авто‑вступление.", "error");
        } else {
          showNotification("Не хватает аккаунтов для роли мониторинга.", "error");
        }
      }
      if (inviteIds.length < inviteCount) {
        if (typeof refreshMembership === "function") {
          await refreshMembership("roles");
        }
        const inviteRoleIds = Object.entries(next)
          .filter(([, roles]) => roles && roles.invite)
          .map(([id]) => Number(id));
        const inviteInOurGroup = inviteRoleIds.filter(
          (id) => membershipStatus && membershipStatus[id] && membershipStatus[id].ourGroupMember
        );
        if (!inviteRoleIds.length) {
          showNotification("Нет инвайт‑бота. Назначьте роль инвайта.", "error");
        } else if (!inviteInOurGroup.length) {
          showNotification("Нет инвайт‑бота в нашей группе. Введите бота в нашу группу или включите авто‑вступление.", "error");
        } else {
          showNotification("Не хватает аккаунтов для роли инвайта.", "error");
        }
      }
      if (taskForm.separateConfirmRoles && confirmIds.length < confirmCount) {
        if (typeof refreshMembership === "function") {
          await refreshMembership("roles");
        }
        const confirmRoleIds = Object.entries(next)
          .filter(([, roles]) => roles && roles.confirm)
          .map(([id]) => Number(id));
        const confirmInOurGroup = confirmRoleIds.filter(
          (id) => membershipStatus && membershipStatus[id] && membershipStatus[id].ourGroupMember
        );
        if (!confirmRoleIds.length) {
          showNotification("Нет подтверждающего бота. Назначьте роль подтверждения.", "error");
        } else if (!confirmInOurGroup.length) {
          showNotification("Нет подтверждающего бота в нашей группе. Введите бота в нашу группу или включите авто‑вступление.", "error");
        } else {
          showNotification("Не хватает аккаунтов для роли подтверждения.", "error");
        }
      }
    }
    const ids = Object.keys(next).map((id) => Number(id));
    setTaskAccountRoles(next);
    setSelectedAccountIds(ids);
    persistAccountRoles(next);
    const label = type === "one" ? "Один бот" : type === "split" ? "Разделить роли" : "Все роли";
    setTaskNotice({ text: `Пресет: ${label}`, tone: "success", source: "accounts" });
  };

  const assignAccountsToTask = async (accountIds) => {
    if (!window.api || selectedTaskId == null) return;
    if (!accountIds.length) return;
    const nextRoles = { ...taskAccountRoles };
    accountIds.forEach((accountId) => {
      if (!nextRoles[accountId]) {
        nextRoles[accountId] = { monitor: true, invite: true, confirm: true };
      }
    });
    const rolePayload = Object.entries(nextRoles).map(([accountId, roles]) => ({
      accountId: Number(accountId),
      roleMonitor: Boolean(roles.monitor),
      roleInvite: Boolean(roles.invite),
      roleConfirm: Boolean(roles.confirm != null ? roles.confirm : roles.invite)
    }));
    const result = await window.api.appendTaskAccounts({
      taskId: selectedTaskId,
      accountRoles: rolePayload
    });
    if (result && result.ok) {
      setTaskAccountRoles(nextRoles);
      setSelectedAccountIds(Object.keys(nextRoles).map((id) => Number(id)));
      await loadAccountAssignments();
    }
  };

  const moveAccountToTask = async (accountId) => {
    if (!window.api || selectedTaskId == null) return;
    await assignAccountsToTask([accountId]);
    setTaskNotice({ text: "Аккаунт добавлен в задачу.", tone: "success", source: "accounts" });
  };

  const removeAccountFromTask = async (accountId) => {
    if (!window.api || selectedTaskId == null) return;
    const result = await window.api.removeTaskAccount({
      taskId: selectedTaskId,
      accountId
    });
    if (result && result.ok) {
      setTaskAccountRoles((prev) => {
        const next = { ...prev };
        delete next[accountId];
        setSelectedAccountIds(Object.keys(next).map((id) => Number(id)));
        return next;
      });
      await loadAccountAssignments();
      setTaskNotice({ text: "Аккаунт удален из задачи.", tone: "success", source: "accounts" });
    }
  };

  const resetCooldown = async (accountId) => {
    if (!window.api) {
      showNotification("Electron API недоступен. Откройте приложение в Electron.", "error");
      return;
    }
    try {
      await window.api.resetAccountCooldown(accountId);
      const updated = await window.api.listAccounts();
      setAccounts(updated);
      setTaskNotice({ text: "Аккаунт снова активен.", tone: "success", source: "accounts" });
    } catch (error) {
      setTaskNotice({ text: error.message || String(error), tone: "error", source: "accounts" });
      showNotification(error.message || String(error), "error");
    }
  };

  const deleteAccount = async (accountId) => {
    if (!window.api) {
      showNotification("Electron API недоступен. Откройте приложение в Electron.", "error");
      return;
    }
    try {
      await window.api.deleteAccount(accountId);
      setAccounts(await window.api.listAccounts());
      setTaskNotice({ text: "Аккаунт удален.", tone: "success", source: "accounts" });
    } catch (error) {
      setTaskNotice({ text: error.message || String(error), tone: "error", source: "accounts" });
      showNotification(error.message || String(error), "error");
    }
  };

  const refreshIdentity = async () => {
    if (!window.api) {
      showNotification("Electron API недоступен. Откройте приложение в Electron.", "error");
      return;
    }
    try {
      await window.api.refreshAccountIdentity();
      setAccounts(await window.api.listAccounts());
      setTaskNotice({ text: "ID аккаунтов обновлены.", tone: "success", source: "accounts" });
    } catch (error) {
      setTaskNotice({ text: error.message || String(error), tone: "error", source: "accounts" });
      showNotification(error.message || String(error), "error");
    }
  };

  return {
    persistAccountRoles,
    resetCooldown,
    deleteAccount,
    refreshIdentity,
    updateAccountRole,
    updateAccountInviteLimit,
    setAccountRolesAll,
    applyRolePreset,
    assignAccountsToTask,
    moveAccountToTask,
    removeAccountFromTask
  };
}
