{% extends "base.html" %}
{% block title %}{{ 'Nuevo usuario' if accion=='nuevo' else 'Editar usuario' }}{% endblock %}
{% block page_title %}{{ 'Añadir usuario al equipo' if accion=='nuevo' else 'Editar usuario' }}{% endblock %}

{% block topbar_actions %}
<a href="{{ url_for('usuarios.index') }}" class="btn btn-outline-secondary btn-sm">
  <i class="bi bi-arrow-left me-1"></i>Volver al equipo
</a>
{% endblock %}

{% block content %}

<div class="row g-4 justify-content-center">
  <div class="col-lg-6">

    {% if error %}
    <div class="alert alert-danger">{{ error }}</div>
    {% endif %}

    <!-- Formulario principal -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header border-0"
           style="background:linear-gradient(135deg,#eef3ff,#e0e7ff)">
        <i class="bi bi-person-badge me-2 text-primary"></i>
        <span class="fw-semibold text-primary">
          {{ 'Nuevo usuario' if accion=='nuevo' else 'Datos del usuario' }}
        </span>
      </div>
      <div class="card-body">
        <form method="post">

          {% if accion == 'nuevo' %}
          <div class="mb-3">
            <label class="form-label">Nombre de usuario <span class="text-danger">*</span></label>
            <input type="text" name="username" class="form-control"
                   placeholder="ej. maria.garcia" required autofocus
                   value="{{ request.form.get('username','') }}">
            <div class="form-text">Sin espacios. Este será el nombre para iniciar sesión.</div>
          </div>
          <div class="row g-3 mb-3">
            <div class="col-6">
              <label class="form-label">Contraseña <span class="text-danger">*</span></label>
              <input type="password" name="password" class="form-control"
                     placeholder="Mín. 6 caracteres" required>
            </div>
            <div class="col-6">
              <label class="form-label">Confirmar <span class="text-danger">*</span></label>
              <input type="password" name="confirm" class="form-control"
                     placeholder="Repetir contraseña" required>
            </div>
          </div>
          {% else %}
          <div class="mb-3 p-3 rounded-2" style="background:#f8fafc">
            <div class="text-muted small mb-1">Usuario</div>
            <div class="fw-bold fs-5">{{ user.username }}</div>
          </div>
          {% endif %}

          <div class="mb-4">
            <label class="form-label fw-semibold">Rol <span class="text-danger">*</span></label>
            <div class="d-flex flex-column gap-2">
              {% for rid, rlabel, rbadge, rdesc in roles %}
              <label class="d-flex align-items-start gap-3 p-3 rounded-2 border cursor-pointer"
                     style="cursor:pointer;transition:background .15s"
                     onclick="this.style.background='#f0f4ff'"
                     onmouseout="this.style.background=''">
                <input type="radio" name="rol" value="{{ rid }}" class="mt-1 flex-shrink-0"
                       {% if (user and user.rol == rid) or (not user and rid == 'contable') %}checked{% endif %}
                       {% if es_yo is defined and es_yo and rid != 'admin' %}disabled{% endif %}>
                <div>
                  <span class="badge {{ rbadge }} mb-1">{{ rlabel }}</span>
                  <div class="small text-muted">{{ rdesc }}</div>
                </div>
              </label>
              {% endfor %}
            </div>
            {% if es_yo is defined and es_yo %}
            <div class="alert alert-info py-2 mt-2" style="font-size:.82rem">
              <i class="bi bi-info-circle me-1"></i>
              No puedes cambiar tu propio rol de administrador.
            </div>
            {% endif %}
          </div>

          {% if accion == 'editar' %}
          <div class="mb-4">
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" name="activo" id="activo"
                     {{ 'checked' if user.activo }}
                     {% if es_yo is defined and es_yo %}disabled{% endif %}>
              <label class="form-check-label fw-semibold" for="activo">Usuario activo</label>
            </div>
            {% if es_yo is defined and es_yo %}
            <div class="form-text">No puedes desactivar tu propia cuenta.</div>
            {% endif %}
          </div>
          {% endif %}

          <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary">
              <i class="bi bi-check2 me-1"></i>
              {{ 'Crear usuario' if accion=='nuevo' else 'Guardar cambios' }}
            </button>
            <a href="{{ url_for('usuarios.index') }}" class="btn btn-outline-secondary">Cancelar</a>
          </div>
        </form>
      </div>
    </div>

    <!-- Reset password (solo al editar) -->
    {% if accion == 'editar' %}
    <div class="card border-0 shadow-sm">
      <div class="card-header border-0" style="background:linear-gradient(135deg,#fff5f5,#fee2e2)">
        <i class="bi bi-key me-2 text-danger"></i>
        <span class="fw-semibold text-danger">Restablecer contraseña</span>
      </div>
      <div class="card-body">
        <form method="post" action="{{ url_for('usuarios.resetear_password', uid=user.id) }}">
          <div class="row g-2 align-items-end">
            <div class="col">
              <label class="form-label">Nueva contraseña</label>
              <input type="password" name="nueva_password" class="form-control"
                     placeholder="Mín. 6 caracteres" required>
            </div>
            <div class="col-auto">
              <button type="submit" class="btn btn-outline-danger"
                      onclick="return confirm('¿Restablecer la contraseña de ' + {{ user.username | tojson }} + '?')">
                <i class="bi bi-key me-1"></i>Restablecer
              </button>
            </div>
          </div>
          <div class="form-text mt-1">
            Comunica la nueva contraseña al usuario de forma segura.
          </div>
        </form>
      </div>
    </div>
    {% endif %}

  </div>
</div>

{% endblock %}
