import { useMemo } from "react";

export default function useAccountComputed({
  accounts,
  accountStats,
  taskAccountRoles,
  accountAssignments,
  selectedTaskId,
  tasks
}) {
  const accountById = useMemo(() => {
    const map = new Map();
    accounts.forEach((account) => {
      map.set(account.id, account);
    });
    return map;
  }, [accounts]);

  const accountStatsMap = useMemo(() => {
    const map = new Map();
    (accountStats || []).forEach((item) => {
      map.set(item.id, item);
    });
    return map;
  }, [accountStats]);

  const roleSummary = useMemo(() => {
    const monitor = [];
    const invite = [];
    const confirm = [];
    Object.entries(taskAccountRoles).forEach(([id, roles]) => {
      const accountId = Number(id);
      if (roles.monitor) monitor.push(accountId);
      if (roles.invite) invite.push(accountId);
      if (roles.confirm) confirm.push(accountId);
    });
    return { monitor, invite, confirm };
  }, [taskAccountRoles]);

  const roleIntersectionCount = useMemo(() => {
    let count = 0;
    Object.values(taskAccountRoles).forEach((roles) => {
      if (roles.monitor && roles.invite) count += 1;
    });
    return count;
  }, [taskAccountRoles]);

  const assignedAccountCount = useMemo(() => {
    const ids = new Set([...roleSummary.monitor, ...roleSummary.invite, ...roleSummary.confirm]);
    return ids.size;
  }, [roleSummary]);

  const assignedAccountMap = useMemo(() => {
    const map = new Map();
    accountAssignments.forEach((row) => {
      const list = map.get(row.account_id) || [];
      list.push({
        taskId: row.task_id,
        roleMonitor: Boolean(row.role_monitor),
        roleInvite: Boolean(row.role_invite),
        roleConfirm: row.role_confirm != null ? Boolean(row.role_confirm) : Boolean(row.role_invite),
        inviteLimit: Number(row.invite_limit || 0)
      });
      map.set(row.account_id, list);
    });
    return map;
  }, [accountAssignments]);

  const filterFreeAccounts = tasks.length > 1;
  const accountBuckets = useMemo(() => {
    const selected = selectedTaskId;
    const freeOrSelected = [];
    const busy = [];
    const taskNameMap = new Map();
    tasks.forEach((task) => {
      taskNameMap.set(task.id, task.name || `Задача #${task.id}`);
    });
    accounts.forEach((account) => {
      const assignedTasks = assignedAccountMap.get(account.id) || [];
      const assignedToSelected = selected != null && assignedTasks.some((item) => item.taskId === selected);
      const isFree = assignedTasks.length === 0;
      if (filterFreeAccounts && !isFree && !assignedToSelected) {
        busy.push(account);
      } else {
        freeOrSelected.push(account);
      }
    });
    return { freeOrSelected, busy, taskNameMap };
  }, [accounts, assignedAccountMap, selectedTaskId, filterFreeAccounts, tasks]);

  const perAccountInviteSum = useMemo(() => {
    return Object.values(taskAccountRoles || {}).reduce((sum, roles) => {
      if (!roles || !roles.invite) return sum;
      const value = Number(roles.inviteLimit || 0);
      return value > 0 ? sum + value : sum;
    }, 0);
  }, [taskAccountRoles]);

  return {
    accountById,
    accountStatsMap,
    roleSummary,
    roleIntersectionCount,
    assignedAccountCount,
    assignedAccountMap,
    filterFreeAccounts,
    accountBuckets,
    perAccountInviteSum
  };
}
