<div class="container-fluid">
  <app-page-title
    title="Gestion des Utilisateurs"
    subTitle="Administrez les utilisateurs Keycloak de votre plateforme"
    [badge]="{icon:'lucideUsers', text:'Keycloak Users'}"
  />

  <!-- Indicateur de permissions -->
  @if (currentUserRole) {
    <div class="row mb-3">
      <div class="col-12">
        <div class="alert alert-info py-2">
          <div class="d-flex align-items-center">
            <ng-icon name="lucideInfo" class="me-2"></ng-icon>
            <div class="flex-grow-1">
              <small>
                <strong>Rôle actuel :</strong> 
                <span class="badge" [ngClass]="getRoleBadgeClass(currentUserRole)">
                  {{ roleService.getRoleLabel(currentUserRole) }}
                </span>
                @if (!canCreateUsers) {
                  <span class="text-warning ms-2">
                    <ng-icon name="lucideShield" class="me-1"></ng-icon>
                    Permissions limitées
                  </span>
                }
              </small>
            </div>
            @if (canCreateUsers) {
              <button
                class="btn btn-primary btn-sm"
                (click)="openCreateUserModal()"
              >
                <ng-icon name="lucideUserPlus" class="me-1"></ng-icon>
                Nouvel Utilisateur
              </button>
            }
          </div>
        </div>
      </div>
    </div>
  }

  <!-- Navigation par onglets avec style bordered -->
  <div class="row mb-4">
    <div class="col-12">
      <ul
        ngbNav
        #usersNav="ngbNav"
        [activeId]="activeTab"
        [destroyOnHide]="false"
        class="nav nav-tabs nav-justified nav-bordered nav-bordered-primary mb-3"
      >
        <li [ngbNavItem]="'list'">
          <a ngbNavLink (click)="showTab('list')">
            <ng-icon name="lucideUsers" class="fs-lg me-md-1 d-inline-flex align-middle" />
            <span class="d-none d-md-inline-block align-middle">Liste des Utilisateurs</span>
          </a>
          <ng-template ngbNavContent>
            <app-users-list 
              [canCreateUsers]="canCreateUsers"
              [canDeleteUsers]="canDeleteUsers"
              (userSelected)="showTab('profile', $event)"
              (openCreateModal)="openCreateUserModal()"
              (openResetPasswordModal)="openResetPasswordModal($event)"
              (openDeleteUserModal)="openDeleteUserModal($event)"
            />
          </ng-template>
        </li>
        
        <li [ngbNavItem]="'profile'" [hidden]="activeTab !== 'profile'">
          <a ngbNavLink (click)="showTab('profile')">
            <ng-icon name="lucideUser" class="fs-lg me-md-1 d-inline-flex align-middle" />
            <span class="d-none d-md-inline-block align-middle">Profil Utilisateur</span>
          </a>
          <ng-template ngbNavContent>
            @if (selectedUserId) {
              <app-user-profile 
                [userId]="selectedUserId"
                (back)="showTab('list')"
              />
            }
          </ng-template>
        </li>
      </ul>

      <div class="tab-content" [ngbNavOutlet]="usersNav"></div>
    </div>
  </div>
</div>

<!-- Modal de création d'utilisateur Keycloak -->
<ng-template #createUserModal let-modal>
  <div class="modal-header">
    <h4 class="modal-title">
      <ng-icon name="lucideUserPlus" class="me-2"></ng-icon>
      Créer un nouvel utilisateur Keycloak
    </h4>
    <button 
      type="button" 
      class="btn-close" 
      (click)="modal.dismiss()"
      [disabled]="creatingUser"
    ></button>
  </div>
  
  <div class="modal-body">
    <!-- Message d'erreur -->
    @if (createUserError) {
      <div class="alert alert-danger d-flex align-items-center">
        <ng-icon name="lucideAlertCircle" class="me-2"></ng-icon>
        <div>{{ createUserError }}</div>
      </div>
    }

    <!-- Avertissement permissions -->
    @if (!canManageRoles && assignableRoles.length === 1) {
      <div class="alert alert-warning">
        <small>
          <ng-icon name="lucideShield" class="me-1"></ng-icon>
          <strong>Permissions limitées :</strong> Vous ne pouvez créer que des utilisateurs avec le rôle 
          <span class="badge" [ngClass]="getRoleBadgeClass(assignableRoles[0])">
            {{ roleService.getRoleLabel(assignableRoles[0]) }}
          </span>
        </small>
      </div>
    }

    <form (ngSubmit)="createUser()" #userForm="ngForm">
      <div class="row g-3">
        <!-- Informations de base -->
        <div class="col-md-6">
          <label class="form-label">
            Prénom <span class="text-danger">*</span>
          </label>
          <input 
            type="text" 
            class="form-control" 
            placeholder="Entrez le prénom"
            [(ngModel)]="newUser.firstName"
            name="firstName"
            required
            [disabled]="creatingUser"
          >
        </div>
        
        <div class="col-md-6">
          <label class="form-label">
            Nom <span class="text-danger">*</span>
          </label>
          <input 
            type="text" 
            class="form-control" 
            placeholder="Entrez le nom"
            [(ngModel)]="newUser.lastName"
            name="lastName"
            required
            [disabled]="creatingUser"
          >
        </div>

        <div class="col-md-6">
          <label class="form-label">
            Nom d'utilisateur <span class="text-danger">*</span>
          </label>
          <input 
            type="text" 
            class="form-control" 
            placeholder="Nom d'utilisateur unique"
            [(ngModel)]="newUser.username"
            name="username"
            required
            [disabled]="creatingUser"
          >
          <div class="form-text">Doit être unique dans Keycloak</div>
        </div>

        <div class="col-md-6">
          <label class="form-label">
            Email <span class="text-danger">*</span>
          </label>
          <input 
            type="email" 
            class="form-control" 
            placeholder="email@exemple.com"
            [(ngModel)]="newUser.email"
            name="email"
            required
            [disabled]="creatingUser"
          >
        </div>

        <div class="col-12">
          <label class="form-label">
            Mot de passe <span class="text-danger">*</span>
          </label>
          <input 
            type="password" 
            class="form-control" 
            placeholder="Mot de passe sécurisé"
            [(ngModel)]="newUser.password"
            name="password"
            required
            minlength="8"
            [disabled]="creatingUser"
          >
          <div class="form-text">
            Le mot de passe doit contenir au moins 8 caractères.
          </div>
        </div>

        <!-- Sélection du rôle -->
        <div class="col-12">
          <label class="form-label">
            Rôle <span class="text-danger">*</span>
          </label>
          <select 
            class="form-select" 
            [(ngModel)]="newUser.role" 
            name="role"
            required
            [disabled]="creatingUser || !canManageRoles"
          >
            <option value="" disabled>Sélectionnez un rôle</option>
            @for (role of availableRoles; track role.value) {
              <option 
                [value]="role.value"
                [disabled]="!canAssignRole(role.value)"
              >
                {{ role.label }} - {{ role.description }}
                @if (!canAssignRole(role.value)) {
                  (Non autorisé)
                }
              </option>
            }
          </select>
          <div class="form-text">
            @if (canManageRoles) {
              Sélectionnez le rôle à assigner à cet utilisateur
            } @else {
              Vous ne pouvez pas modifier les rôles disponibles
            }
          </div>
        </div>

        <!-- Aperçu du rôle sélectionné -->
        @if (newUser.role) {
          <div class="col-12">
            <div class="alert alert-info">
              <div class="d-flex align-items-center">
                <ng-icon 
                  [name]="roleService.getRoleIcon(newUser.role)" 
                  class="me-2"
                ></ng-icon>
                <div>
                  <strong>Rôle sélectionné :</strong>
                  <span class="badge ms-2" [ngClass]="getRoleBadgeClass(newUser.role)">
                    {{ roleService.getRoleLabel(newUser.role) }}
                  </span>
                  <br>
                  <small class="text-muted">
                    {{ getRoleDescription(newUser.role) }}
                  </small>
                </div>
              </div>
            </div>
          </div>
        }

        <!-- Configuration du compte -->
        <div class="col-md-6">
          <div class="form-check form-switch">
            <input 
              class="form-check-input" 
              type="checkbox" 
              id="enabledSwitch"
              [(ngModel)]="newUser.enabled"
              name="enabled"
              [disabled]="creatingUser"
            >
            <label class="form-check-label" for="enabledSwitch">
              Compte activé
            </label>
          </div>
          <div class="form-text">L'utilisateur peut se connecter immédiatement</div>
        </div>

        <div class="col-md-6">
          <div class="form-check form-switch">
            <input 
              class="form-check-input" 
              type="checkbox" 
              id="emailVerifiedSwitch"
              [(ngModel)]="newUser.emailVerified"
              name="emailVerified"
              [disabled]="creatingUser"
            >
            <label class="form-check-label" for="emailVerifiedSwitch">
              Email vérifié
            </label>
          </div>
          <div class="form-text">L'utilisateur n'aura pas à vérifier son email</div>
        </div>
      </div>

      <div class="modal-footer mt-4">
        <button 
          type="button" 
          class="btn btn-light" 
          (click)="modal.dismiss()"
          [disabled]="creatingUser"
        >
          Annuler
        </button>
        <button 
          type="submit" 
          class="btn btn-primary"
          [disabled]="!userForm.form.valid || creatingUser || !canAssignRole(newUser.role)"
        >
          @if (creatingUser) {
            <div class="spinner-border spinner-border-sm me-2" role="status">
              <span class="visually-hidden">Chargement...</span>
            </div>
            Création...
          } @else {
            <ng-icon name="lucideUserPlus" class="me-1"></ng-icon>
            Créer l'utilisateur
          }
        </button>
      </div>
    </form>
  </div>
</ng-template>

<!-- Modal de réinitialisation de mot de passe -->
<ng-template #resetPasswordModal let-modal>
  <div class="modal-header">
    <h4 class="modal-title">
      <ng-icon name="lucideKey" class="me-2"></ng-icon>
      Réinitialiser le mot de passe
    </h4>
    <button 
      type="button" 
      class="btn-close" 
      (click)="modal.dismiss()"
      [disabled]="resettingPassword"
    ></button>
  </div>
  
  <div class="modal-body">
    <!-- Message de succès -->
    @if (resetPasswordSuccess) {
      <div class="alert alert-success d-flex align-items-center">
        <ng-icon name="lucideCheckCircle" class="me-2"></ng-icon>
        <div>{{ resetPasswordSuccess }}</div>
      </div>
    }

    <!-- Message d'erreur -->
    @if (resetPasswordError) {
      <div class="alert alert-danger d-flex align-items-center">
        <ng-icon name="lucideAlertCircle" class="me-2"></ng-icon>
        <div>{{ resetPasswordError }}</div>
      </div>
    }

    @if (!resetPasswordSuccess && selectedUserForReset) {
      <div class="alert alert-info">
        <div class="d-flex align-items-center">
          <ng-icon 
            [name]="roleService.getRoleIcon(selectedUserForReset.role)" 
            class="me-2"
          ></ng-icon>
          <div>
            <strong>Utilisateur :</strong> {{ selectedUserForReset.username }}
            @if (selectedUserForReset.firstName || selectedUserForReset.lastName) {
              <br>
              <strong>Nom :</strong> {{ selectedUserForReset.firstName }} {{ selectedUserForReset.lastName }}
            }
            <br>
            <strong>Rôle :</strong> 
            <span class="badge ms-1" [ngClass]="getRoleBadgeClass(selectedUserForReset.role)">
              {{ roleService.getRoleLabel(selectedUserForReset.role) }}
            </span>
          </div>
        </div>
      </div>

      <form (ngSubmit)="confirmResetPassword()" #resetForm="ngForm">
        <div class="mb-3">
          <label class="form-label">
            Nouveau mot de passe <span class="text-danger">*</span>
          </label>
          <input 
            type="password" 
            class="form-control" 
            placeholder="Entrez le nouveau mot de passe"
            [(ngModel)]="newPassword"
            name="newPassword"
            required
            minlength="8"
            [disabled]="resettingPassword"
          >
          <div class="form-text">
            Le mot de passe doit contenir au moins 8 caractères.
          </div>
        </div>

        <div class="mb-3">
          <div class="form-check">
            <input 
              class="form-check-input" 
              type="checkbox" 
              id="temporaryPassword"
              [(ngModel)]="temporaryPassword"
              name="temporaryPassword"
              [disabled]="resettingPassword"
            >
            <label class="form-check-label" for="temporaryPassword">
              Mot de passe temporaire
            </label>
          </div>
          <div class="form-text">
            L'utilisateur devra changer son mot de passe à la prochaine connexion.
          </div>
        </div>
      </form>
    }
  </div>

  <div class="modal-footer">
    @if (resetPasswordSuccess) {
      <button 
        type="button" 
        class="btn btn-success"
        (click)="modal.close()"
      >
        <ng-icon name="lucideCheck" class="me-1"></ng-icon>
        Fermer
      </button>
    } @else {
      <button 
        type="button" 
        class="btn btn-light" 
        (click)="modal.dismiss()"
        [disabled]="resettingPassword"
      >
        Annuler
      </button>
      <button 
        type="button" 
        class="btn btn-primary"
        (click)="confirmResetPassword()"
        [disabled]="!newPassword || newPassword.length < 8 || resettingPassword"
      >
        @if (resettingPassword) {
          <div class="spinner-border spinner-border-sm me-2" role="status">
            <span class="visually-hidden">Chargement...</span>
          </div>
          Réinitialisation...
        } @else {
          <ng-icon name="lucideKey" class="me-1"></ng-icon>
          Réinitialiser le mot de passe
        }
      </button>
    }
  </div>
</ng-template>

<!-- Modal de confirmation de suppression -->
<ng-template #deleteUserModal let-modal>
  <div class="modal-header">
    <h4 class="modal-title text-danger">
      <ng-icon name="lucideTrash2" class="me-2"></ng-icon>
      Confirmer la suppression
    </h4>
    <button 
      type="button" 
      class="btn-close" 
      (click)="modal.dismiss()"
    ></button>
  </div>
  
  <div class="modal-body text-center">
    <div class="mb-4">
      <div class="avatar-lg mx-auto mb-3 bg-danger bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center">
        <ng-icon name="lucideUserX" class="text-danger" style="font-size: 2rem;"></ng-icon>
      </div>
      <h5 class="text-danger mb-2">Êtes-vous sûr de vouloir supprimer cet utilisateur ?</h5>
      <p class="text-muted mb-0">
        Cette action est irréversible. Toutes les données de 
        <strong>{{ selectedUserForDelete?.username }}</strong> seront définitivement perdues.
      </p>
    </div>

    @if (selectedUserForDelete) {
      <div class="alert alert-warning">
        <div class="d-flex align-items-start">
          <ng-icon name="lucideAlertTriangle" class="me-2 mt-1"></ng-icon>
          <div>
            <strong>Utilisateur :</strong> {{ selectedUserForDelete.username }}
            @if (selectedUserForDelete.firstName || selectedUserForDelete.lastName) {
              <br>
              <strong>Nom :</strong> {{ selectedUserForDelete.firstName }} {{ selectedUserForDelete.lastName }}
            }
            <br>
            <strong>Email :</strong> {{ selectedUserForDelete.email }}
            <br>
            <strong>Rôle :</strong> 
            <span class="badge ms-1" [ngClass]="getRoleBadgeClass(selectedUserForDelete.role)">
              {{ roleService.getRoleLabel(selectedUserForDelete.role) }}
            </span>
          </div>
        </div>
      </div>
    }

    <!-- Message d'erreur -->
    @if (deleteUserError) {
      <div class="alert alert-danger d-flex align-items-center">
        <ng-icon name="lucideAlertCircle" class="me-2"></ng-icon>
        <div>{{ deleteUserError }}</div>
      </div>
    }
  </div>

  <div class="modal-footer">
    <button 
      type="button" 
      class="btn btn-light" 
      (click)="modal.dismiss()"
      [disabled]="deletingUser"
    >
      <ng-icon name="lucideX" class="me-1"></ng-icon>
      Annuler
    </button>
    <button 
      type="button" 
      class="btn btn-danger"
      (click)="confirmDeleteUser()"
      [disabled]="deletingUser || !canDeleteUsers"
    >
      @if (deletingUser) {
        <div class="spinner-border spinner-border-sm me-2" role="status">
          <span class="visually-hidden">Suppression...</span>
        </div>
        Suppression...
      } @else {
        <ng-icon name="lucideTrash2" class="me-1"></ng-icon>
        Supprimer définitivement
      }
    </button>
  </div>
</ng-template>