import React, { memo, useState } from "react";

function AccountsTab({
  accounts,
  accountStatsMap,
  settings,
  membershipStatus,
  assignedAccountMap,
  accountBuckets,
  filterFreeAccounts,
  selectedAccountIds,
  taskAccountRoles,
  hasSelectedTask,
  taskNotice,
  refreshMembership,
  refreshIdentity,
  formatAccountStatus,
  resetCooldown,
  deleteAccount,
  updateAccountRole,
  setAccountRolesAll,
  applyRolePreset,
  removeAccountFromTask,
  moveAccountToTask
}) {
  const [membershipModal, setMembershipModal] = useState(null);

  const openMembershipModal = (title, lines) => {
    setMembershipModal({ title, lines });
  };

  const closeMembershipModal = () => {
    setMembershipModal(null);
  };

  const buildAccountLabel = (account) => `${account.username ? `@${account.username}` : "—"} (${account.user_id || "—"})`;

  const roleStats = React.useMemo(() => {
    const knownIds = new Set((accounts || []).map((account) => account.id));
    let monitor = 0;
    let invite = 0;
    let total = 0;
    Object.entries(taskAccountRoles || {}).forEach(([id, roles]) => {
      const accountId = Number(id);
      if (!knownIds.has(accountId)) return;
      if (roles.monitor) monitor += 1;
      if (roles.invite) invite += 1;
      if (roles.monitor || roles.invite) total += 1;
    });
    return { monitor, invite, total };
  }, [taskAccountRoles, accounts]);
  return (
    <section className="card">
      <div className="row-header">
        <h2>Аккаунты</h2>
        <div className="row-inline">
          <button className="ghost" type="button" onClick={() => refreshMembership("accounts")}>Проверить участие</button>
          <button className="ghost" type="button" onClick={refreshIdentity}>Обновить ID</button>
        </div>
      </div>
      <div className="hint">
        Отметьте аккаунты для выбранной задачи. При нескольких задачах здесь показываются свободные аккаунты.
      </div>
      {!hasSelectedTask && (
        <div className="hint">Выберите задачу, чтобы управлять аккаунтами.</div>
      )}
      {taskNotice && taskNotice.source === "accounts" && (
        <div className={`notice inline ${taskNotice.tone}`}>{taskNotice.text}</div>
      )}
      {hasSelectedTask && (
        <div className="account-summary">
          Роли: мониторинг — {roleStats.monitor}, инвайт — {roleStats.invite}, всего — {roleStats.total}
        </div>
      )}
      {hasSelectedTask && (
        <div className="role-presets">
          <button className="secondary" type="button" onClick={() => applyRolePreset("one")}>Один бот</button>
          <button className="secondary" type="button" onClick={() => applyRolePreset("split")}>Разделить роли</button>
          <button className="secondary" type="button" onClick={() => applyRolePreset("all")}>Все роли</button>
        </div>
      )}
      <div className="account-list">
        {accounts.length === 0 && <div className="empty">Аккаунты не добавлены.</div>}
        {accountBuckets.freeOrSelected.map((account) => {
          const assignedTasks = assignedAccountMap.get(account.id) || [];
          const membership = membershipStatus[account.id];
          const stats = accountStatsMap.get(account.id);
          const remaining = stats && stats.remainingToday != null ? stats.remainingToday : null;
          const used = stats ? stats.usedToday : 0;
          const limit = stats ? stats.limit : settings.accountDailyLimit;
          const cooldownUntil = account.cooldown_until ? new Date(account.cooldown_until).getTime() : 0;
          const cooldownActive = cooldownUntil > Date.now();
          const cooldownMinutes = cooldownActive ? Math.ceil((cooldownUntil - Date.now()) / 60000) : 0;
          const accountLabel = buildAccountLabel(account);
          const competitorLines = membership && Array.isArray(membership.competitorGroups)
            ? membership.competitorGroups
              .filter((item) => item.isMember)
              .map((item) => item.title || item.link)
            : [];
          const ourLines = membership && membership.ourGroup && membership.ourGroup.isMember
            ? [membership.ourGroup.title || membership.ourGroup.link || "—"]
            : [];
          const competitorInfo = membership
            ? `В конкурентах: ${membership.competitorCount}/${membership.competitorTotal}`
            : "В конкурентах: —";
          const ourInfo = membership
            ? `В нашей: ${membership.ourGroupMember ? "да" : "нет"}`
            : "В нашей: —";
          const selected = selectedAccountIds.includes(account.id);
          const roles = taskAccountRoles[account.id] || { monitor: false, invite: false };
          const taskNames = assignedTasks
            .map((item) => {
              const name = accountBuckets.taskNameMap.get(item.taskId) || `Задача #${item.taskId}`;
              const roles = [
                item.roleMonitor ? "М" : null,
                item.roleInvite ? "И" : null
              ].filter(Boolean).join("/");
              return roles ? `${name} (${roles})` : name;
            })
            .join(", ");

          return (
            <div key={account.id} className="account-row">
              <div>
                <div className="account-phone">{account.phone}</div>
                <div className={`status ${account.status}`}>{formatAccountStatus(account.status)}</div>
                <div className="role-badges">
                  {roles.monitor && <span className="role-pill">Мониторинг</span>}
                  {roles.invite && <span className="role-pill">Инвайт</span>}
                </div>
                <div className="account-meta">User ID: {account.user_id || "—"}</div>
                <div className="account-meta membership-row">
                  <strong>{competitorInfo}</strong>
                  {membership && (
                    <button
                      className="ghost tiny"
                      type="button"
                      onClick={() => openMembershipModal(`Конкуренты — ${accountLabel}`, competitorLines)}
                    >
                      Список
                    </button>
                  )}
                </div>
                <div className="account-meta membership-row">
                  <strong>{ourInfo}</strong>
                  {membership && (
                    <button
                      className="ghost tiny"
                      type="button"
                      onClick={() => openMembershipModal(`Наша группа — ${accountLabel}`, ourLines)}
                    >
                      Подробнее
                    </button>
                  )}
                </div>
                <div className="account-meta">Лимит групп: {account.max_groups || settings.accountMaxGroups}</div>
                <div className="account-meta">Лимит действий: {account.daily_limit || settings.accountDailyLimit}</div>
                <div className="account-meta">
                  Осталось действий сегодня: {remaining == null ? "без лимита" : remaining} (использовано: {used}/{limit || "∞"})
                </div>
                <div className="account-meta">Работает в задачах: {assignedTasks.length ? taskNames : "—"}</div>
                {cooldownActive && (
                  <div className="account-meta">
                    Таймер FLOOD: {cooldownMinutes} мин
                  </div>
                )}
              </div>
              {account.status !== "ok" && account.last_error && (
                <div className="account-error">{account.last_error}</div>
              )}
              <div className="account-actions">
                {hasSelectedTask && (
                  <div className="role-toggle">
                    <label className="checkbox">
                      <input
                        type="checkbox"
                        checked={Boolean(roles.monitor)}
                        onChange={(event) => updateAccountRole(account.id, "monitor", event.target.checked)}
                      />
                      Мониторинг
                    </label>
                    <label className="checkbox">
                      <input
                        type="checkbox"
                        checked={Boolean(roles.invite)}
                        onChange={(event) => updateAccountRole(account.id, "invite", event.target.checked)}
                      />
                      Инвайт
                    </label>
                    <button
                      className="ghost tiny"
                      type="button"
                      onClick={() => setAccountRolesAll(account.id, !selected)}
                    >
                      {selected ? "Снять роли" : "Оба"}
                    </button>
                  </div>
                )}
                {hasSelectedTask && selected && (
                  <button className="ghost" onClick={() => removeAccountFromTask(account.id)}>
                    Убрать из задачи
                  </button>
                )}
                {cooldownActive && (
                  <button className="secondary" onClick={() => resetCooldown(account.id)}>
                    Снять ограничение
                  </button>
                )}
                <button className="danger" onClick={() => deleteAccount(account.id)}>
                  Удалить
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {filterFreeAccounts && accountBuckets.busy.length > 0 && (
        <div className="busy-accounts">
          <div className="row-header">
            <h3>Занятые аккаунты</h3>
            <div className="status-caption">Используются в других задачах</div>
          </div>
          <div className="account-list">
            {accountBuckets.busy.map((account) => {
              const assignedTasks = assignedAccountMap.get(account.id) || [];
              const taskNames = assignedTasks
                .map((item) => {
                  const name = accountBuckets.taskNameMap.get(item.taskId) || `Задача #${item.taskId}`;
                  const roles = [
                    item.roleMonitor ? "М" : null,
                    item.roleInvite ? "И" : null
                  ].filter(Boolean).join("/");
                  return roles ? `${name} (${roles})` : name;
                })
                .join(", ");
              const membership = membershipStatus[account.id];
              const stats = accountStatsMap.get(account.id);
              const remaining = stats && stats.remainingToday != null ? stats.remainingToday : null;
              const used = stats ? stats.usedToday : 0;
              const limit = stats ? stats.limit : settings.accountDailyLimit;
              const cooldownUntil = account.cooldown_until ? new Date(account.cooldown_until).getTime() : 0;
              const cooldownActive = cooldownUntil > Date.now();
              const cooldownMinutes = cooldownActive ? Math.ceil((cooldownUntil - Date.now()) / 60000) : 0;
              const accountLabel = buildAccountLabel(account);
              const competitorLines = membership && Array.isArray(membership.competitorGroups)
                ? membership.competitorGroups
                  .filter((item) => item.isMember)
                  .map((item) => item.title || item.link)
                : [];
              const ourLines = membership && membership.ourGroup && membership.ourGroup.isMember
                ? [membership.ourGroup.title || membership.ourGroup.link || "—"]
                : [];
              const competitorInfo = membership
                ? `В конкурентах: ${membership.competitorCount}/${membership.competitorTotal}`
                : "В конкурентах: —";
              const ourInfo = membership
                ? `В нашей: ${membership.ourGroupMember ? "да" : "нет"}`
                : "В нашей: —";

              return (
                <div key={account.id} className="account-row">
                  <div>
                    <div className="account-phone">{account.phone}</div>
                    <div className={`status ${account.status}`}>{formatAccountStatus(account.status)}</div>
                    <div className="role-badges">
                      {roles.monitor && <span className="role-pill">Мониторинг</span>}
                      {roles.invite && <span className="role-pill">Инвайт</span>}
                    </div>
                    <div className="account-meta">User ID: {account.user_id || "—"}</div>
                    <div className="account-meta membership-row">
                      <strong>{competitorInfo}</strong>
                      {membership && (
                        <button
                          className="ghost tiny"
                          type="button"
                          onClick={() => openMembershipModal(`Конкуренты — ${accountLabel}`, competitorLines)}
                        >
                          Список
                        </button>
                      )}
                    </div>
                    <div className="account-meta membership-row">
                      <strong>{ourInfo}</strong>
                      {membership && (
                        <button
                          className="ghost tiny"
                          type="button"
                          onClick={() => openMembershipModal(`Наша группа — ${accountLabel}`, ourLines)}
                        >
                          Подробнее
                        </button>
                      )}
                    </div>
                    <div className="account-meta">Лимит групп: {account.max_groups || settings.accountMaxGroups}</div>
                    <div className="account-meta">Лимит действий: {account.daily_limit || settings.accountDailyLimit}</div>
                    <div className="account-meta">
                      Осталось действий сегодня: {remaining == null ? "без лимита" : remaining} (использовано: {used}/{limit || "∞"})
                    </div>
                    <div className="account-meta">Работает в задачах: {assignedTasks.length ? taskNames : "—"}</div>
                    {cooldownActive && (
                      <div className="account-meta">
                        Таймер FLOOD: {cooldownMinutes} мин
                      </div>
                    )}
                  </div>
                  {account.status !== "ok" && account.last_error && (
                    <div className="account-error">{account.last_error}</div>
                  )}
                  <div className="account-actions">
                    {cooldownActive && (
                      <button className="secondary" onClick={() => resetCooldown(account.id)}>
                        Снять ограничение
                      </button>
                    )}
                    {hasSelectedTask && (
                      <button className="secondary" onClick={() => moveAccountToTask(account.id)}>
                        Добавить в задачу
                      </button>
                    )}
                    <button className="danger" onClick={() => deleteAccount(account.id)}>
                      Удалить
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
      {membershipModal && (
        <div className="modal-overlay" onClick={closeMembershipModal}>
          <div className="modal" onClick={(event) => event.stopPropagation()}>
            <div className="row-header">
              <h3>{membershipModal.title}</h3>
              <button className="ghost" type="button" onClick={closeMembershipModal}>Закрыть</button>
            </div>
            {membershipModal.lines && membershipModal.lines.length > 0 ? (
              <div className="modal-list">
                {membershipModal.lines.map((line) => (
                  <div key={line} className="modal-list-item">{line}</div>
                ))}
              </div>
            ) : (
              <div className="status-text">Нет групп.</div>
            )}
          </div>
        </div>
      )}
    </section>
  );
}

export default memo(AccountsTab);
