{# File: plugins/admin/templates/admin/users/list.html #}
{% extends 'core/base.html' %}
{% block title %}Users – Admin – Nature In Pots{% endblock %}
{% block content %}
<h1>Users</h1>

<form method="get" class="row g-2 mb-3">
  <div class="col-auto">
    <input id="searchInput" type="text"
           name="q"
           value="{{ q }}"
           class="form-control"
           placeholder="Search by email…">
  </div>
  <div class="col-auto">
    <button type="submit" class="btn btn-primary">Search</button>
  </div>
  <div class="col-auto form-check align-self-center">
    <input id="showDeleted" type="checkbox"
           class="form-check-input"
           name="show_deleted"
           value="1"
           {% if show_deleted %}checked{% endif %}>
    <label class="form-check-label" for="showDeleted">
      Show deleted
    </label>
  </div>
</form>

<p>
  <a href="{{ url_for('admin.create_user') }}"
     class="btn btn-primary mb-3">
    Create New User
  </a>
</p>

<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Email</th>
      <th>Role</th>
      <th>Verified</th>
      <th>Excluded</th>
      <th>Status</th>
      <th>Joined</th>
      <th>Invites Remaining</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody id="userTableBody">
    {% for u in users %}
    <tr>
      <td>{{ u.id }}</td>
      <td>
        <a href="{{ url_for('user.profile', user_id=u.id) }}">
          {{ u.email }}
        </a>
      </td>
      <td>{{ u.role }}</td>
      <td>{{ '✓' if u.is_verified else '' }}</td>
      <td>{{ '✓' if u.excluded_from_analytics else '' }}</td>
      <td>
        {% if u.is_banned %}
          <span class="text-danger">Permanently Banned</span>
        {% elif u.suspended_until and u.suspended_until > utcnow %}
          <span class="text-warning">
            Suspended until {{ u.suspended_until.strftime('%Y-%m-%d') }}
          </span>
        {% else %}
          <span class="text-success">Active</span>
        {% endif %}
      </td>
      <td>{{ u.created_at.strftime('%Y-%m-%d') }}</td>
      <td>{{ u.invites_remaining }}</td>
      <td>
        <a href="{{ url_for('admin.edit_user',
                             user_id=u.id,
                             page=pagination.page,
                             show_deleted='1' if show_deleted else None,
                             q=q) }}"
           class="btn btn-sm btn-primary">Edit</a>

        <a href="{{ url_for('admin.adjust_invites', user_id=u.id) }}"
           class="btn btn-sm btn-info">Adjust Invites</a>

        <a href="{{ url_for('admin.list_invitations', user_id=u.id) }}"
           class="btn btn-sm btn-warning">Invitations</a>

        {% if u.is_deleted %}
          <form action="{{ url_for('admin.undelete_user',
                                    user_id=u.id,
                                    page=pagination.page,
                                    show_deleted='1',
                                    q=q) }}"
                method="post" style="display:inline;">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button type="submit"
                    class="btn btn-sm btn-success"
                    onclick="return confirm('Restore this user?');">
              Restore
            </button>
          </form>
        {% else %}
          <form action="{{ url_for('admin.delete_user',
                                    user_id=u.id,
                                    page=pagination.page,
                                    show_deleted='1' if show_deleted else None,
                                    q=q) }}"
                method="post" style="display:inline;">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button type="submit"
                    class="btn btn-sm btn-danger"
                    onclick="return confirm('Delete this user?');">
              Delete
            </button>
          </form>
        {% endif %}
      </td>
    </tr>
    {% endfor %}
  </tbody>
</table>

<nav id="paginationNav" aria-label="User list pagination">
  <ul class="pagination">
    {% if pagination.has_prev %}
      <li class="page-item">
        <a class="page-link"
           href="{{ url_for('admin.list_users',
                             page=pagination.prev_num,
                             show_deleted='1' if show_deleted else None,
                             q=q) }}">
          Previous
        </a>
      </li>
    {% else %}
      <li class="page-item disabled">
        <span class="page-link">Previous</span>
      </li>
    {% endif %}

    {% for p in pagination.iter_pages(left_edge=2, right_edge=2,
                                      left_current=2, right_current=2) %}
      {% if p %}
        {% if p == pagination.page %}
          <li class="page-item active">
            <span class="page-link">{{ p }}</span>
          </li>
        {% else %}
          <li class="page-item">
            <a class="page-link"
               href="{{ url_for('admin.list_users',
                                 page=p,
                                 show_deleted='1' if show_deleted else None,
                                 q=q) }}">
              {{ p }}
            </a>
          </li>
        {% endif %}
      {% else %}
        <li class="page-item disabled">
          <span class="page-link">…</span>
        </li>
      {% endif %}
    {% endfor %}

    {% if pagination.has_next %}
      <li class="page-item">
        <a class="page-link"
           href="{{ url_for('admin.list_users',
                             page=pagination.next_num,
                             show_deleted='1' if show_deleted else None,
                             q=q) }}">
          Next
        </a>
      </li>
    {% else %}
      <li class="page-item disabled">
        <span class="page-link">Next</span>
      </li>
    {% endif %}
  </ul>
</nav>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const searchInput         = document.getElementById('searchInput');
  const showDeletedCheckbox = document.getElementById('showDeleted');
  const tbody               = document.getElementById('userTableBody');
  const paginationNav       = document.getElementById('paginationNav');
  const listUrl             = "{{ url_for('admin.list_users') }}";

  let timer;
  function doSearch() {
    const q           = searchInput.value;
    const showDeleted = showDeletedCheckbox.checked ? '1' : '0';

    fetch(`${listUrl}?q=${encodeURIComponent(q)}&show_deleted=${showDeleted}`, {
      headers: {'X-Requested-With': 'XMLHttpRequest'}
    })
    .then(r => r.json())
    .then(data => {
      tbody.innerHTML = '';
      data.users.forEach(u => {
        let statusHtml;
        if (u.status === 'banned') {
          statusHtml = '<span class="text-danger">Permanently Banned</span>';
        } else if (u.status === 'suspended') {
          statusHtml = `<span class="text-warning">Suspended until ${u.suspended_until}</span>`;
        } else {
          statusHtml = '<span class="text-success">Active</span>';
        }

        const actionForms = u.is_deleted
          ? `<form action="/admin/users/${u.id}/undelete" method="post" style="display:inline;">
               <input type="hidden" name="csrf_token" value="${data.csrf_token}">
               <button type="submit" class="btn btn-sm btn-success" onclick="return confirm('Restore this user?');">Restore</button>
             </form>`
          : `<form action="/admin/users/${u.id}/delete" method="post" style="display:inline;">
               <input type="hidden" name="csrf_token" value="${data.csrf_token}">
               <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Delete this user?');">Delete</button>
             </form>`;

        tbody.insertAdjacentHTML('beforeend', `
          <tr>
            <td>${u.id}</td>
            <td><a href="/users/${u.id}/profile/">\${u.email}</a></td>
            <td>${u.role}</td>
            <td>${u.is_verified ? '✓' : ''}</td>
            <td>${u.excluded_from_analytics ? '✓' : ''}</td>
            <td>${statusHtml}</td>
            <td>${u.created_at}</td>
            <td>${u.invites_remaining}</td>
            <td>
              <a href="/admin/users/${u.id}/edit" class="btn btn-sm btn-primary">Edit</a>
              <a href="/admin/users/${u.id}/adjust-invites" class="btn btn-sm btn-info">Adjust Invites</a>
              <a href="/admin/invitations?user_id=${u.id}" class="btn btn-sm btn-warning">Invitations</a>
              ${actionForms}
            </td>
          </tr>
        `);
      });
      paginationNav.style.display = q ? 'none' : '';
    });
  }

  searchInput.addEventListener('input', () => {
    clearTimeout(timer);
    timer = setTimeout(doSearch, 300);
  });
  showDeletedCheckbox.addEventListener('change', () => {
    clearTimeout(timer);
    timer = setTimeout(doSearch, 0);
  });
});
</script>
{% endblock %}
