{% extends 'plantilla.html' %}
{% load static %}

{% block head %}
{{ block.super }}

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css">

<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

<style>
  table.dataTable thead th { white-space: nowrap; }

  .dataTables_wrapper .dataTables_filter {
    text-align: right;
    padding: 12px 16px 0 16px;
  }
  .dataTables_wrapper .dataTables_filter label {
    font-weight: 600;
    color: #2c3e50;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    margin: 0;
  }
  .dataTables_wrapper .dataTables_filter input {
    border-radius: 12px !important;
    border: 2px solid #e9ecef !important;
    padding: 10px 14px !important;
    outline: none;
    transition: all 0.25s ease;
    width: 260px;
    max-width: 100%;
  }
  .dataTables_wrapper .dataTables_filter input:focus {
    border-color: #f39c12 !important;
    box-shadow: 0 0 0 0.25rem rgba(243, 156, 18, 0.15) !important;
    transform: translateY(-1px);
  }
  @media (max-width: 768px) {
    .dataTables_wrapper .dataTables_filter {
      text-align: left;
      padding: 12px 16px 0 16px;
    }
    .dataTables_wrapper .dataTables_filter input {
      width: 100%;
    }
  }
</style>
{% endblock %}

{% block body %}

<main class="container-fluid py-3">
  <!-- HEADER MEJORADO -->
  <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4">
    <div class="mb-3 mb-md-0">
      <h1 class="fw-bold text-dark mb-1">Gestión de Usuarios</h1>
      <p class="text-muted mb-0">Administración de usuarios del sistema</p>
    </div>
    
    <div class="d-flex align-items-center gap-3">
      <span class="badge bg-primary-subtle text-primary fs-6 fw-normal px-3 py-2">
        <i class="fas fa-users me-2"></i>{{ usuario|length }} usuarios
      </span>
      <a href="{% url 'nuevo_usuario' %}" class="btn btn-primary px-4 py-2">
        <i class="fas fa-user-plus me-2"></i>Nuevo Usuario
      </a>
    </div>
  </div>
  
  <hr class="border-2 opacity-50 mb-5">

  <div class="card border-0 shadow-lg">
    <div class="card-body p-0">
      <div class="table-responsive">
        <table id="table_usuarios" class="table table-hover align-middle mb-0">
          <thead class="bg-dark text-white">
            <tr>
              <th class="ps-4 py-3">ID</th>
              <th class="py-3">Nombres</th>
              <th class="py-3">Apellidos</th>
              <th class="py-3">Mesa</th>
              <th class="py-3">Cargo</th>
              <th class="py-3">Usuario</th>
              <th class="text-center pe-4 py-3">Acciones</th>
            </tr>
          </thead>

          <tbody>
            {% for u in usuario %}
            <tr class="border-bottom">
              <td class="ps-4 fw-semibold text-primary">#{{ u.id }}</td>
              
              <td>
                <div class="d-flex align-items-center">
                  <div class="bg-primary-subtle rounded-circle p-2 me-3">
                    <i class="fas fa-user text-primary"></i>
                  </div>
                  <div>
                    <div class="fw-medium text-dark">{{ u.nombres }}</div>
                  </div>
                </div>
              </td>
              
              <td>
                <div class="fw-medium text-dark">{{ u.apellidos }}</div>
              </td>
              
              <td>
                <span class="badge bg-warning text-dark fs-6 px-3 py-2">
                  <i class="fas fa-chair me-1"></i>{{ u.mesa }}
                </span>
              </td>
              
              <td>
                <span class="badge bg-info-subtle text-info px-3 py-2">
                  {{ u.cargo }}
                </span>
              </td>
              
              <td>
                <div class="fw-medium text-dark">{{ u.username }}</div>
                <small class="text-muted">Usuario</small>
              </td>

              <td class="text-center pe-4">
                <div class="btn-group btn-group-sm" role="group">
                  <!-- EDITAR -->
                  <button class="btn btn-outline-warning"
                          data-bs-toggle="modal"
                          data-bs-target="#modalEditar{{ u.id }}">
                    <i class="fas fa-edit"></i>
                  </button>

                  <!-- ELIMINAR -->
                  <a href="{% url 'eliminar_usuario' u.id %}"
                     class="btn btn-outline-danger btn-eliminar"
                     data-nombre="{{ u.nombres }} {{ u.apellidos }}"
                     data-id="{{ u.id }}">
                    <i class="fas fa-trash-alt"></i>
                  </a>
                </div>
              </td>
            </tr>
            {% empty %}
            <tr>
              <td colspan="7" class="text-center py-5">
                <div class="py-5">
                  <i class="fas fa-users fa-3x text-muted mb-3"></i>
                  <h5 class="text-muted">No hay usuarios registrados</h5>
                  <p class="text-muted">Agrega un nuevo usuario para comenzar</p>
                </div>
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>
</main>

{% for u in usuario %}
<div class="modal fade" id="modalEditar{{ u.id }}" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header bg-gradient-warning text-dark border-0">
        <div class="d-flex align-items-center w-100">
          <div class="bg-white rounded-circle p-2 me-3">
            <i class="fas fa-user-edit fa-lg text-warning"></i>
          </div>
          <div>
            <h5 class="modal-title fw-bold mb-0">Editar Usuario</h5>
            <small class="text-dark">Modifica la información del usuario</small>
          </div>
        </div>
        <button type="button" class="btn-close btn-close-dark" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body p-4">
        <form action="{% url 'procesar_edicion_usuario' %}"
              method="post"
              class="form_usuario"
              autocomplete="off">
          {% csrf_token %}
          <input type="hidden" name="id" value="{{ u.id }}">

          <div class="row g-4">
            <!-- COLUMNA IZQUIERDA -->
            <div class="col-md-6">
              <div class="mb-4">
                <label class="form-label fw-semibold text-dark d-flex align-items-center mb-3">
                  <i class="fas fa-user text-primary me-2"></i>Nombres
                </label>
                <input class="form-control border-2" 
                       type="text" 
                       name="nombres" 
                       value="{{ u.nombres }}" 
                       required
                       placeholder="Ingrese los nombres">
              </div>
              
              <div class="mb-4">
                <label class="form-label fw-semibold text-dark d-flex align-items-center mb-3">
                  <i class="fas fa-user text-primary me-2"></i>Apellidos
                </label>
                <input class="form-control border-2" 
                       type="text" 
                       name="apellidos" 
                       value="{{ u.apellidos }}" 
                       required
                       placeholder="Ingrese los apellidos">
              </div>
              
              <div class="mb-4">
                <label class="form-label fw-semibold text-dark d-flex align-items-center mb-3">
                  <i class="fas fa-chair text-warning me-2"></i>Mesa
                </label>
                <select class="form-select border-2" name="mesa" required>
                  <option value="">-- Seleccionar mesa --</option>
                  {% for m in mesas %}
                    <option value="{{ m.nombre }}" {% if u.mesa == m.nombre %}selected{% endif %}>
                      {{ m.nombre }}
                    </option>
                  {% endfor %}
                </select>
              </div>
            </div>
            
            <!-- COLUMNA DERECHA -->
            <div class="col-md-6">
              <div class="mb-4">
                <label class="form-label fw-semibold text-dark d-flex align-items-center mb-3">
                  <i class="fas fa-briefcase text-info me-2"></i>Cargo
                </label>
                <input class="form-control border-2" 
                       type="text" 
                       name="cargo" 
                       value="{{ u.cargo }}" 
                       required
                       placeholder="Ingrese el cargo">
              </div>
              
              <div class="mb-4">
                <label class="form-label fw-semibold text-dark d-flex align-items-center mb-3">
                  <i class="fas fa-user-circle text-success me-2"></i>Usuario (username)
                </label>
                <input class="form-control border-2" 
                       type="text" 
                       name="username" 
                       value="{{ u.username }}" 
                       required
                       placeholder="Nombre de usuario">
                <small class="text-muted mt-2 d-block">
                  <i class="fas fa-info-circle me-1"></i>Debe ser único en el sistema.
                </small>
              </div>
              
              <div class="mb-4">
                <label class="form-label fw-semibold text-dark d-flex align-items-center mb-3">
                  <i class="fas fa-key text-danger me-2"></i>Nueva contraseña
                </label>
                <input class="form-control border-2" 
                       type="password" 
                       name="password"
                       placeholder="•••••••••••••••">
                <small class="text-muted mt-2 d-block">
                  <i class="fas fa-info-circle me-1"></i>Dejar vacío para mantener la contraseña actual.
                </small>
              </div>
            </div>
          </div>
          
          <div class="alert alert-warning border-2 mt-4">
            <div class="d-flex">
              <i class="fas fa-exclamation-triangle fa-2x me-3 text-warning"></i>
              <div>
                <h6 class="fw-bold mb-1">Información importante</h6>
                <small class="mb-0">Los cambios se aplicarán inmediatamente al sistema.</small>
              </div>
            </div>
          </div>
        </form>
      </div>

      <div class="modal-footer bg-light border-top">
        <button type="button" class="btn btn-lg btn-outline-secondary px-4" data-bs-dismiss="modal">
          <i class="fas fa-times me-2"></i>Cancelar
        </button>

        <button type="submit" class="btn btn-lg btn-success px-4"
                onclick="$(this).closest('.modal-content').find('form.form_usuario').submit();">
          <i class="fas fa-save me-2"></i>Guardar Cambios
        </button>
      </div>
    </div>
  </div>
</div>
{% endfor %}

<br><br>
{% endblock %}

{% block extra_scripts %}

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>


<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>


<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>


<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(function () {

  // Validación: Solo letras
  $.validator.addMethod("lettersOnly", function(value, element) {
    return this.optional(element) || /^[A-Za-zÁÉÍÓÚáéíóúÑñ\s]+$/.test(value);
  }, "Solo letras, por favor.");

  $('.form_usuario').each(function() {
    $(this).validate({
      ignore: [],
      rules: {
        nombres: { required: true, lettersOnly: true, minlength: 3, maxlength: 100 },
        apellidos: { required: true, lettersOnly: true, minlength: 3, maxlength: 100 },
        mesa: { required: true },
        cargo: { required: true, maxlength: 100 },
        username: { required: true, minlength: 3, maxlength: 50 },
        password: { minlength: 6 }
      },
      messages: {
        nombres: { 
          required: "Por favor ingrese los nombres.", 
          minlength: "Debe tener al menos 3 caracteres.", 
          maxlength: "No puede superar 100 caracteres." 
        },
        apellidos: { 
          required: "Por favor ingrese los apellidos.", 
          minlength: "Debe tener al menos 3 caracteres.", 
          maxlength: "No puede superar 100 caracteres." 
        },
        mesa: { required: "Por favor seleccione una mesa." },
        cargo: { 
          required: "Por favor ingrese el cargo.", 
          maxlength: "No puede superar 100 caracteres." 
        },
        username: { 
          required: "Por favor ingrese el usuario (username).", 
          minlength: "Debe tener al menos 3 caracteres.", 
          maxlength: "No puede superar 50 caracteres." 
        },
        password: { 
          minlength: "Si vas a cambiar la contraseña, debe tener al menos 6 caracteres." 
        }
      },
      errorElement: 'div',
      errorClass: 'error text-danger small mt-2',
      errorPlacement: function (error, element) { 
        error.insertAfter(element); 
      },
      highlight: function (element) { 
        $(element).addClass('is-invalid border-danger'); 
      },
      unhighlight: function (element) { 
        $(element).removeClass('is-invalid border-danger'); 
      },
      submitHandler: function(form) { 
        form.submit(); 
      }
    });
  });


  const tabla = $('#table_usuarios').DataTable({
    responsive: true,

  
    dom: '<"row"<"col-sm-12 col-md-4"l><"col-sm-12 col-md-4 text-md-center"f><"col-sm-12 col-md-4 d-flex justify-content-md-end"B>>rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',

    buttons: [
      {
        extend: 'copy',
        text: '<i class="fas fa-copy me-2"></i>Copiar',
        className: 'btn btn-secondary'
      },
      {
        extend: 'csv',
        text: '<i class="fas fa-file-csv me-2"></i>CSV',
        className: 'btn btn-dark'
      },
      {
        extend: 'excel',
        text: '<i class="fas fa-file-excel me-2"></i>Excel',
        className: 'btn btn-success'
      },
      {
        extend: 'pdf',
        text: '<i class="fas fa-file-pdf me-2"></i>PDF',
        className: 'btn btn-warning'
      },
      {
        extend: 'print',
        text: '<i class="fas fa-print me-2"></i>Imprimir',
        className: 'btn btn-info'
      }
    ],
    language: {
      url: 'https://cdn.datatables.net/plug-ins/1.13.7/i18n/es-ES.json'
    },
    lengthMenu: [[5, 10, 25, 50, 100, -1],[5, 10, 25, 50, 100, "Todos"]],
    pageLength: 10,
    columnDefs: [
      { orderable: false, targets: [6] }
    ]
  });

 
  $(document).on('click', '.btn-eliminar', function(e){
    e.preventDefault();

    const url = $(this).attr('href');
    const nombre = $(this).data('nombre') || 'este usuario';

    Swal.fire({
      title: "¿Eliminar usuario?",
      html: `<div class="text-center py-3">
              <i class="fas fa-user-times fa-4x text-danger mb-4"></i>
              <h4 class="fw-bold">${nombre}</h4>
              <p class="text-muted mt-3">Esta acción no se puede deshacer</p>
            </div>`,
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "<i class='fas fa-trash me-2'></i>Eliminar",
      cancelButtonText: "<i class='fas fa-times me-2'></i>Cancelar",
      confirmButtonColor: "#dc3545",
      cancelButtonColor: "#6c757d",
      reverseButtons: true,
      customClass: {
        confirmButton: 'btn btn-lg btn-danger',
        cancelButton: 'btn btn-lg btn-secondary'
      }
    }).then((result) => {
      if (result.isConfirmed) window.location.href = url;
    });
  });

});
</script>

<style>
  /* ESTILOS MEJORADOS SOLO VISUALES */
  body { 
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
  }
  
  /* GRADIENTES */
  .bg-gradient-warning {
    background: linear-gradient(135deg, #f39c12 0%, #f1c40f 100%) !important;
  }
  
  /* TABLA MEJORADA */
  .table {
    --bs-table-bg: transparent;
    --bs-table-striped-bg: rgba(0,0,0,0.02);
  }
  
  .table > thead {
    background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  }
  
  .table > thead th {
    border-bottom: 3px solid #f39c12;
    font-weight: 700;
    letter-spacing: 0.5px;
    padding: 1rem;
  }
  
  .table-hover tbody tr:hover {
    background: linear-gradient(90deg, rgba(243, 156, 18, 0.08) 0%, rgba(243, 156, 18, 0.04) 100%);
    transform: translateY(-1px);
    transition: all 0.3s ease;
  }
  
  .border-bottom {
    border-bottom: 2px solid rgba(0,0,0,0.05) !important;
  }
  
  /* BOTONES MEJORADOS */
  .btn {
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.3s ease;
    border-width: 2px;
  }
  
  .btn-outline-warning {
    border-color: #f39c12;
    color: #f39c12;
  }
  
  .btn-outline-warning:hover {
    background: linear-gradient(135deg, #f39c12 0%, #f1c40f 100%);
    color: white;
    border-color: transparent;
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(243, 156, 18, 0.3);
  }
  
  .btn-outline-danger {
    border-color: #e74c3c;
    color: #e74c3c;
  }
  
  .btn-outline-danger:hover {
    background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
    color: white;
    border-color: transparent;
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(231, 76, 60, 0.3);
  }
  
  .btn-outline-secondary {
    border-color: #95a5a6;
    color: #95a5a6;
  }
  
  .btn-outline-secondary:hover {
    background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
    color: white;
    border-color: transparent;
  }
  
  .btn-success {
    background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
    border: none;
  }
  
  .btn-success:hover {
    background: linear-gradient(135deg, #229954 0%, #27ae60 100%);
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(39, 174, 96, 0.3);
  }
  
  .btn-primary {
    background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
    border: none;
  }
  
  .btn-primary:hover {
    background: linear-gradient(135deg, #2980b9 0%, #1f6396 100%);
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
  }
  
  /* FORMULARIOS MEJORADOS */
  .form-control, .form-select {
    border-radius: 12px;
    border: 2px solid #e9ecef;
    padding: 12px 16px;
    transition: all 0.3s ease;
    font-size: 1rem;
  }
  
  .form-control:focus, .form-select:focus {
    border-color: #f39c12;
    box-shadow: 0 0 0 0.25rem rgba(243, 156, 18, 0.15);
    transform: translateY(-1px);
  }
  
  .border-2 {
    border-width: 2px !important;
  }
  
  /* BADGES MEJORADOS */
  .badge {
    border-radius: 50px;
    font-weight: 600;
    padding: 8px 16px;
  }
  
  .bg-primary-subtle {
    background-color: rgba(52, 152, 219, 0.1) !important;
    border: 1px solid rgba(52, 152, 219, 0.2);
  }
  
  .bg-warning {
    background: linear-gradient(135deg, #f39c12 0%, #f1c40f 100%) !important;
  }
  
  .bg-info-subtle {
    background-color: rgba(52, 152, 219, 0.1) !important;
    border: 1px solid rgba(52, 152, 219, 0.2);
  }
  
  /* CARD MEJORADA */
  .card {
    border-radius: 16px;
    border: none;
  }
  
  .shadow-lg {
    box-shadow: 0 10px 30px rgba(0,0,0,0.12) !important;
  }
  
  /* MODAL MEJORADO */
  .modal-content {
    border-radius: 20px;
    border: none;
    box-shadow: 0 20px 60px rgba(0,0,0,0.2);
  }
  
  .modal-header {
    border-radius: 20px 20px 0 0;
    padding: 1.5rem 2rem;
  }
  
  .modal-body {
    padding: 2rem;
  }
  
  .modal-footer {
    border-radius: 0 0 20px 20px;
    padding: 1.5rem 2rem;
  }
  
  .btn-close-dark {
    filter: invert(1) grayscale(100%) brightness(200%);
  }
  
  /* ALERTAS */
  .alert {
    border-radius: 12px;
  }
  
  /* ANIMACIONES SUAVES */
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  .card, .modal-content {
    animation: fadeInUp 0.5s ease-out;
  }
  
  /* SCROLLBAR PERSONALIZADA */
  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  
  ::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
  }
  
  ::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #f39c12 0%, #f1c40f 100%);
    border-radius: 10px;
  }
  
  /* RESPONSIVE */
  @media (max-width: 768px) {
    .table-responsive {
      border: 1px solid #dee2e6;
      border-radius: 15px;
    }
    
    .btn-group {
      flex-direction: column;
      gap: 5px;
    }
    
    .btn-group .btn {
      border-radius: 8px;
      width: 40px;
      height: 40px;
    }
    
    .modal-body {
      padding: 1.5rem;
    }
  }
  
  /* HR MEJORADO */
  hr {
    border-top: 3px solid rgba(243, 156, 18, 0.2);
    opacity: 1;
  }
</style>

{% endblock %}
