import { buildPresetSignature } from "../utils/presets.js";
import { sanitizeTaskForm } from "../appDefaults.js";

export default function useTaskPresets({
  hasSelectedTask,
  accounts,
  selectedAccountIds,
  taskForm,
  setTaskForm,
  setTaskAccountRoles,
  setSelectedAccountIds,
  persistAccountRoles,
  showNotification,
  setTaskNotice,
  setActivePreset,
  setActiveTab,
  selectedTaskId,
  presetSignatureRef
}) {
  const applyTaskPreset = (type) => {
    if (!hasSelectedTask) {
      showNotification("Сначала выберите задачу.", "error");
      return;
    }
    if (!accounts.length) {
      showNotification("Нет доступных аккаунтов.", "error");
      return;
    }
    const masterId = accounts[0].id;
    const requiredCount = 3;
    const baseIds = selectedAccountIds.length >= requiredCount
      ? selectedAccountIds.slice()
      : accounts.map((account) => account.id);
    if (baseIds.length < 3) {
      showNotification("Для раздельных ролей желательно минимум 3 аккаунта (мониторинг/инвайт/подтверждение).", "info");
    }
    if (!baseIds.includes(masterId)) {
      baseIds.unshift(masterId);
    }
    const pool = baseIds.filter((id) => id !== masterId);
    const roleMap = {};
    const addRole = (id, role) => {
      if (!id) return;
      if (!roleMap[id]) roleMap[id] = { monitor: false, invite: false, confirm: false, inviteLimit: 0 };
      roleMap[id][role] = true;
      if (role === "invite" && (!roleMap[id].inviteLimit || roleMap[id].inviteLimit === 0)) {
        roleMap[id].inviteLimit = 1;
      }
    };
    const takeFromPool = (count, used) => {
      const result = [];
      for (const id of pool) {
        if (result.length >= count) break;
        if (used.has(id)) continue;
        used.add(id);
        result.push(id);
      }
      return result;
    };
    const used = new Set();
    const isSoft = type === "soft_50" || type === "soft_50_admin" || type === "soft_25" || type === "soft_25_admin";
    const isSoft25 = type === "soft_25" || type === "soft_25_admin";
    const monitorCount = 1;
    const inviteCount = isSoft ? (isSoft25 ? 2 : 5) : 1;
    const confirmCount = 1;
    const monitorIds = takeFromPool(monitorCount, used);
    const confirmIds = takeFromPool(confirmCount, used);
    const inviteIds = masterId ? [masterId] : takeFromPool(inviteCount, used);
    if (monitorIds.length < monitorCount) addRole(masterId, "monitor");
    if (confirmIds.length < confirmCount) addRole(masterId, "confirm");
    monitorIds.forEach((id) => addRole(id, "monitor"));
    confirmIds.forEach((id) => addRole(id, "confirm"));
    inviteIds.forEach((id) => addRole(id, "invite"));

    const nextForm = sanitizeTaskForm({
      ...taskForm,
      warmupEnabled: true,
      historyLimit: 35,
      separateBotRoles: true,
      requireSameBotInBoth: false,
      maxCompetitorBots: 1,
      maxOurBots: isSoft ? (isSoft25 ? 2 : 5) : 1,
      separateConfirmRoles: true,
      maxConfirmBots: isSoft ? 1 : 1,
      inviteViaAdmins: type === "admin" || type === "soft_50_admin" || type === "soft_25_admin",
      inviteAdminAnonymous: true,
      inviteAdminMasterId: masterId,
      rolesMode: "auto",
      dailyLimit: isSoft ? (isSoft25 ? 25 : 50) : taskForm.dailyLimit,
      maxInvitesPerCycle: isSoft ? (isSoft25 ? 2 : 5) : taskForm.maxInvitesPerCycle,
      minIntervalMinutes: isSoft ? 3 : taskForm.minIntervalMinutes,
      maxIntervalMinutes: isSoft ? 6 : taskForm.maxIntervalMinutes,
      retryOnFail: isSoft ? true : taskForm.retryOnFail,
      stopOnBlocked: isSoft ? true : taskForm.stopOnBlocked,
      stopBlockedPercent: isSoft ? 25 : taskForm.stopBlockedPercent,
      randomAccounts: isSoft ? false : taskForm.randomAccounts,
      multiAccountsPerRun: isSoft ? false : taskForm.multiAccountsPerRun,
      inviteLinkOnFail: isSoft ? false : taskForm.inviteLinkOnFail,
      allowStartWithoutInviteRights: isSoft ? false : taskForm.allowStartWithoutInviteRights
    });
    const signature = buildPresetSignature(nextForm, roleMap);
    presetSignatureRef.current = signature;
    const label = type === "admin"
      ? "Автораспределение + Инвайт через админа"
      : type === "no_admin"
        ? "Автораспределение + Без админки"
        : type === "soft_50_admin"
          ? "Мягкий 50/день + Инвайт через админов"
          : type === "soft_25_admin"
            ? "Мягкий 25/день + Инвайт через админов"
            : type === "soft_25"
              ? "Мягкий 25/день (2 инвайтера)"
              : "Мягкий режим 50/день (5 инвайтеров)";
    setTaskForm(nextForm);
    setTaskAccountRoles(roleMap);
    setSelectedAccountIds(Object.keys(roleMap).map((id) => Number(id)));
    persistAccountRoles(roleMap);
    if (window.api) {
      window.api.addAccountEvent({
        accountId: 0,
        phone: "",
        action: "preset_applied",
        details: `задача ${selectedTaskId}: ${label}`
      });
    }
    setTaskNotice({ text: `Пресет: ${label}`, tone: "success", source: "task" });
    setActivePreset(type);
    setActiveTab("events");
  };

  return { applyTaskPreset };
}
