{% set admin_page = "users" %}
{% extends "admin/base_admin.html" %}

{% block title %}Users - {{ config.APP_NAME }} Admin{% endblock %}
{% block topbar_title %}Users{% endblock %}

{% block admin_content %}
  <!-- Search -->
  <form method="get" class="mb-6">
    <div class="flex gap-3 max-w-md">
      <input type="search" name="search" class="form-input" placeholder="Search by email..." value="{{ search }}">
      <button type="submit" class="btn">Search</button>
    </div>
  </form>

  <!-- User Table -->
  <div class="card" style="padding:0;overflow:hidden;">
    {% if users %}
    <div class="overflow-x-auto">
      <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Email</th>
            <th>Name</th>
            <th>Plan</th>
            <th>Joined</th>
            <th>Last Login</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {% for u in users %}
          <tr>
            <td class="mono text-sm">{{ u.id }}</td>
            <td><a href="{{ url_for('admin.user_detail', user_id=u.id) }}">{{ u.email }}</a></td>
            <td>{{ u.name or '-' }}</td>
            <td>
              {% if u.plan %}
              <span class="badge">{{ u.plan }}</span>
              {% else %}
              <span class="text-sm text-stone">free</span>
              {% endif %}
            </td>
            <td class="mono text-sm">{{ u.created_at[:10] }}</td>
            <td class="mono text-sm">{{ u.last_login_at[:10] if u.last_login_at else 'Never' }}</td>
            <td>
              <form method="post" action="{{ url_for('admin.impersonate', user_id=u.id) }}" class="m-0">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <button type="submit" class="btn-outline btn-sm">Impersonate</button>
              </form>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <div class="flex gap-4 justify-center" style="padding:16px;">
      {% if page > 1 %}
      <a href="?page={{ page - 1 }}{% if search %}&search={{ search }}{% endif %}" class="text-sm">&larr; Previous</a>
      {% endif %}
      <span class="text-stone text-sm">Page {{ page }}</span>
      {% if users | length == 50 %}
      <a href="?page={{ page + 1 }}{% if search %}&search={{ search }}{% endif %}" class="text-sm">Next &rarr;</a>
      {% endif %}
    </div>
    {% else %}
    <p class="text-stone text-sm" style="padding:16px;">No users found.</p>
    {% endif %}
  </div>
{% endblock %}
