<div x-data="portalUsuariosApp()" x-init="init()" class="p-6">

  <div class="flex items-center justify-between mb-6">
    <div>
      <h1 class="text-2xl font-bold text-slate-800">Usuarios del Portal</h1>
      <p class="text-sm text-slate-500 mt-1">Accesos del portal de clientes</p>
    </div>
    <button @click="openCreate()" class="btn-primary flex items-center gap-2">
      <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
      Nuevo usuario
    </button>
  </div>

  <!-- Tabla -->
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-x-auto">
    <table class="w-full text-sm">
      <thead class="bg-slate-50 text-slate-500 text-xs uppercase tracking-wide">
        <tr>
          <th class="px-4 py-3 text-left">Nombre</th>
          <th class="px-4 py-3 text-left">Email</th>
          <th class="px-4 py-3 text-left">Rol</th>
          <th class="px-4 py-3 text-left">Cliente / Accesos</th>
          <th class="px-4 py-3 text-left">Estado</th>
          <th class="px-4 py-3 text-left">Acciones</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-100">
        <template x-if="loading">
          <tr><td colspan="6" class="text-center py-10 text-slate-400">Cargando...</td></tr>
        </template>
        <template x-for="u in items" :key="u.ID">
          <tr class="hover:bg-slate-50">
            <td class="px-4 py-3 font-medium text-slate-800" x-text="u.nombre"></td>
            <td class="px-4 py-3 text-slate-600" x-text="u.email"></td>
            <td class="px-4 py-3">
              <span class="badge" :class="(u.role?.es_portal_partner || u.rol==='partner') ? 'badge-blue' : 'badge-green'" x-text="u.role?.name || u.rol"></span>
            </td>
            <td class="px-4 py-3 text-slate-500 text-xs">
              <template x-if="!(u.role?.es_portal_partner || u.rol==='partner') && u.cliente">
                <span x-text="u.cliente?.empresa || u.cliente?.nombre"></span>
              </template>
              <template x-if="u.role?.es_portal_partner || u.rol==='partner'">
                <div class="flex flex-wrap gap-1">
                  <template x-for="acc in (u.portal_accesos||[])" :key="acc.ID">
                    <span class="bg-slate-100 px-2 py-0.5 rounded text-xs flex items-center gap-1">
                      <span x-text="acc.cliente?.empresa || acc.cliente?.nombre || acc.cliente_id"></span>
                      <button @click="removeAcceso(u, acc.cliente_id)" class="text-red-400 hover:text-red-600 ml-1">&times;</button>
                    </span>
                  </template>
                  <button @click="openAddAcceso(u)" class="text-primary text-xs hover:underline">+ Agregar</button>
                </div>
              </template>
            </td>
            <td class="px-4 py-3">
              <span :class="u.activo ? 'badge-green' : 'badge-slate'" class="badge" x-text="u.activo ? 'Activo' : 'Inactivo'"></span>
            </td>
            <td class="px-4 py-3 flex gap-2">
              <button @click="openEdit(u)" class="btn-icon text-yellow-500" title="Editar">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
              </button>
              <button @click="confirmDelete(u)" class="btn-icon text-red-500" title="Eliminar">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
              </button>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </div>

  <!-- Modal crear/editar -->
  <div x-show="showModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showModal=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4 p-6">
      <h2 class="text-lg font-bold mb-4" x-text="editId ? 'Editar usuario' : 'Nuevo usuario'"></h2>
      <form @submit.prevent="save()">
        <div class="space-y-3">
          <div><label class="label">Nombre</label><input x-model="form.nombre" class="input-field w-full" required></div>
          <div><label class="label">Email</label><input x-model="form.email" type="email" class="input-field w-full" required></div>
          <div>
            <label class="label">Contraseña <span class="normal-case font-normal text-slate-400" x-show="editId">(dejar vacío para no cambiar)</span></label>
            <input x-model="form.password" type="password" class="input-field w-full" :required="!editId">
          </div>
          <div>
            <label class="label">Rol</label>
            <select x-model.number="form.role_id" class="input-field w-full">
              <option value="">Sin rol asignado</option>
              <template x-for="r in portalRoles" :key="r.ID">
                <option :value="r.ID">
                  <span x-text="r.name + (r.es_portal_partner ? ' (Partner)' : ' (Cliente)')"></span>
                </option>
              </template>
            </select>
          </div>
          <div x-show="portalRoles.find(r => r.ID === form.role_id)?.es_portal_cliente">
            <label class="label">Cliente asignado</label>
            <select x-model.number="form.cliente_id" class="input-field w-full">
              <option value="">Sin asignar</option>
              <template x-for="c in clientes" :key="c.ID">
                <option :value="c.ID" x-text="c.empresa || c.nombre"></option>
              </template>
            </select>
          </div>
          <div>
            <label class="label">Activo</label>
            <input type="checkbox" x-model="form.activo" class="w-4 h-4">
          </div>
          <div><label class="label">Notas</label><textarea x-model="form.notas" class="input-field w-full" rows="2"></textarea></div>
        </div>
        <p x-show="error" x-text="error" class="text-red-500 text-sm mt-3"></p>
        <div class="flex justify-end gap-3 mt-5">
          <button type="button" @click="showModal=false" class="btn-secondary">Cancelar</button>
          <button type="submit" :disabled="saving" class="btn-primary" x-text="saving?'Guardando...':'Guardar'"></button>
        </div>
      </form>
    </div>
  </div>

  <!-- Modal agregar acceso (partner) -->
  <div x-show="showAccesoModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showAccesoModal=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-sm mx-4 p-6">
      <h2 class="text-lg font-bold mb-4">Agregar acceso a cliente</h2>
      <label class="label">Cliente</label>
      <select x-model.number="accesoClienteId" class="input-field w-full mb-4">
        <option value="">Seleccionar...</option>
        <template x-for="c in clientes" :key="c.ID">
          <option :value="c.ID" x-text="c.empresa || c.nombre"></option>
        </template>
      </select>
      <div class="flex justify-end gap-3">
        <button @click="showAccesoModal=false" class="btn-secondary">Cancelar</button>
        <button @click="addAcceso()" :disabled="!accesoClienteId" class="btn-primary">Agregar</button>
      </div>
    </div>
  </div>

  <!-- Modal eliminar -->
  <div x-show="showDelete" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showDelete=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-sm mx-4 p-6">
      <h2 class="text-lg font-bold mb-2">¿Eliminar usuario?</h2>
      <p class="text-slate-500 text-sm mb-5">Se revocará el acceso al portal.</p>
      <div class="flex justify-end gap-3">
        <button @click="showDelete=false" class="btn-secondary">Cancelar</button>
        <button @click="doDelete()" :disabled="saving" class="btn-danger" x-text="saving?'Eliminando...':'Eliminar'"></button>
      </div>
    </div>
  </div>

</div>

<script>
function portalUsuariosApp() {
  return {
    items: [], clientes: [], portalRoles: [], loading: false, saving: false,
    showModal: false, showDelete: false, showAccesoModal: false,
    editId: null, deleteId: null, error: '',
    accesoUserId: null, accesoClienteId: '',
    form: { nombre:'', email:'', password:'', role_id:'', cliente_id:'', activo:true, notas:'' },

    async init() { await this.load(); },

    async load() {
      this.loading = true;
      try {
        const r = await axios.get('/app/loadportalusuarios');
        this.items = r.data.items || [];
        this.clientes = r.data.clientes || [];
        this.portalRoles = r.data.portalRoles || [];
      } finally { this.loading = false; }
    },

    openCreate() {
      this.editId=null; this.error='';
      this.form={nombre:'',email:'',password:'',role_id:'',cliente_id:'',activo:true,notas:''};
      this.showModal=true;
    },
    openEdit(u) {
      this.editId=u.ID; this.error='';
      this.form={nombre:u.nombre,email:u.email,password:'',role_id:u.role_id||'',cliente_id:u.cliente_id||'',activo:u.activo,notas:u.notas||''};
      this.showModal=true;
    },
    async save() {
      this.saving=true; this.error='';
      const payload={...this.form};
      if(payload.cliente_id==='') payload.cliente_id=null;
      if(payload.role_id==='') payload.role_id=null;
      try {
        if(this.editId) await axios.put(`/app/portal-usuarios/${this.editId}`, payload);
        else await axios.post('/app/portal-usuarios', payload);
        this.showModal=false; await this.load();
      } catch(e) { this.error=e.response?.data?.error||'Error al guardar'; }
      finally { this.saving=false; }
    },
    confirmDelete(u) { this.deleteId=u.ID; this.showDelete=true; },
    async doDelete() {
      this.saving=true;
      try { await axios.delete(`/app/portal-usuarios/${this.deleteId}`); this.showDelete=false; await this.load(); }
      finally { this.saving=false; }
    },

    openAddAcceso(u) { this.accesoUserId=u.ID; this.accesoClienteId=''; this.showAccesoModal=true; },
    async addAcceso() {
      await axios.post(`/app/portal-usuarios/${this.accesoUserId}/acceso`, {cliente_id: this.accesoClienteId});
      this.showAccesoModal=false; await this.load();
    },
    async removeAcceso(u, clienteId) {
      if(!confirm('¿Quitar acceso a este cliente?')) return;
      await axios.delete(`/app/portal-usuarios/${u.ID}/acceso/${clienteId}`);
      await this.load();
    },
  }
}
</script>

<style>
.btn-primary{background:#8eb02f;color:#fff;padding:.5rem 1rem;border-radius:.5rem;font-weight:600;font-size:.875rem;}
.btn-primary:hover{background:#6d8c24;}
.btn-secondary{background:#f1f5f9;color:#475569;padding:.5rem 1rem;border-radius:.5rem;font-weight:500;font-size:.875rem;border:1px solid #e2e8f0;}
.btn-danger{background:#ef4444;color:#fff;padding:.5rem 1rem;border-radius:.5rem;font-weight:600;font-size:.875rem;}
.btn-icon{display:inline-flex;align-items:center;padding:.25rem;border-radius:.375rem;}
.btn-icon:hover{background:#f1f5f9;}
.input-field{border:1px solid #e2e8f0;border-radius:.5rem;padding:.5rem .75rem;font-size:.875rem;outline:none;}
.input-field:focus{border-color:#8eb02f;}
.label{display:block;font-size:.75rem;font-weight:600;color:#475569;margin-bottom:.25rem;text-transform:uppercase;letter-spacing:.05em;}
.badge{display:inline-block;padding:.15rem .6rem;border-radius:9999px;font-size:.7rem;font-weight:600;text-transform:capitalize;}
.badge-green{background:#dcfce7;color:#15803d;}
.badge-blue{background:#dbeafe;color:#1d4ed8;}
.badge-slate{background:#f1f5f9;color:#475569;}
.text-primary{color:#8eb02f;}
</style>
