{% extends "base.html" %}

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

{% block content %}
<main class="container">
  <header style="display: flex; justify-content: space-between; align-items: center;">
    <h1>Users</h1>
    <a href="{{ url_for('admin.index') }}" role="button" class="secondary outline">← Dashboard</a>
  </header>
  
  <!-- Search -->
  <form method="get" style="margin-bottom: 2rem;">
    <div class="grid">
      <input 
        type="search" 
        name="search" 
        placeholder="Search by email..." 
        value="{{ search }}"
      >
      <button type="submit">Search</button>
    </div>
  </form>
  
  <!-- User Table -->
  <article>
    {% if users %}
    <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>{{ 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 %}
            <mark>{{ u.plan }}</mark>
            {% else %}
            free
            {% endif %}
          </td>
          <td>{{ u.created_at[:10] }}</td>
          <td>{{ 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) }}" style="margin: 0;">
              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
              <button type="submit" class="outline secondary" style="padding: 0.25rem 0.5rem; margin: 0;">
                Impersonate
              </button>
            </form>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    
    <!-- Pagination -->
    <div style="display: flex; gap: 1rem; justify-content: center; margin-top: 1rem;">
      {% if page > 1 %}
      <a href="?page={{ page - 1 }}{% if search %}&search={{ search }}{% endif %}">← Previous</a>
      {% endif %}
      <span>Page {{ page }}</span>
      {% if users | length == 50 %}
      <a href="?page={{ page + 1 }}{% if search %}&search={{ search }}{% endif %}">Next →</a>
      {% endif %}
    </div>
    {% else %}
    <p>No users found.</p>
    {% endif %}
  </article>
</main>
{% endblock %}
