<ng-container *transloco="let t; prefix: 'settingsUsers'">
<div class="main-container">
  <div class="settings-header">
    <h2 class="settings-title">
      <i class="pi pi-users"></i>
      {{ t('title') }}
    </h2>
    <p class="settings-description">
      {{ t('description') }}
    </p>
  </div>

  <div class="settings-card">
    <div class="section-header">
      <div class="section-header-row">
        <div class="section-header-text">
          <h3 class="section-title">
            <i class="pi pi-user"></i>
            {{ t('currentUsers.sectionTitle') }}
          </h3>
          <p class="section-description">
            {{ t('currentUsers.sectionDesc') }}
          </p>
        </div>
        <p-button
          icon="pi pi-plus"
          [label]="t('currentUsers.addUser')"
          severity="success"
          size="small"
          [outlined]="true"
          (onClick)="openCreateUserDialog()">
        </p-button>
      </div>
    </div>

    <div class="section-body">
      @if (users.length === 0) {
        <div class="empty-state">
          <i class="pi pi-users"></i>
          <p class="empty-title">{{ t('emptyState.title') }}</p>
          <p class="empty-subtitle">{{ t('emptyState.subtitle') }}</p>
        </div>
      } @else {
        <div class="users-list">
          @for (user of users; track user.id) {
            <div class="user-card" [class.is-expanded]="isRowExpanded(user)" [class.is-admin]="user.permissions.admin">
              <div class="user-card-header">
                <div class="user-main-info">
                  <button
                    type="button"
                    class="expand-btn"
                    (click)="toggleRowExpansion(user)">
                    <i [class]="isRowExpanded(user) ? 'pi pi-chevron-down' : 'pi pi-chevron-right'"></i>
                  </button>

                  <div class="user-avatar">
                    {{ user.username.charAt(0).toUpperCase() }}
                  </div>

                  <div class="user-identity">
                    <div class="user-name-row">
                      <span class="username">{{ user.username }}</span>
                      <span class="user-type-badge" [attr.data-type]="user.provisioningMethod || 'LOCAL'">
                        {{ (user.provisioningMethod || 'LOCAL') | lowercase | titlecase }}
                      </span>
                      @if (user.permissions.admin) {
                        <span class="admin-badge">
                          <i class="pi pi-shield"></i>
                          {{ t('admin') }}
                        </span>
                      }
                    </div>
                    @if (user.name || user.email) {
                      <div class="user-meta">
                        @if (user.name) {
                          <span class="user-fullname">{{ user.name }}</span>
                        }
                        @if (user.name && user.email) {
                          <span class="meta-separator">·</span>
                        }
                        @if (user.email) {
                          <span class="user-email">{{ user.email }}</span>
                        }
                      </div>
                    }
                  </div>
                </div>

                <div class="user-summary">
                  <div class="permission-badges">
                    <div class="permission-badge" [attr.data-level]="getPermissionLevel(getBookManagementPermissionsCount(user), 5)"
                         [pTooltip]="t('permBadges.bookMgmt', { count: getBookManagementPermissionsCount(user) })">
                      <i class="pi pi-book"></i>
                      <span>{{ getBookManagementPermissionsCount(user) }}/5</span>
                    </div>
                    <div class="permission-badge" [attr.data-level]="getPermissionLevel(getSystemAccessPermissionsCount(user), 3)"
                         [pTooltip]="t('permBadges.systemAccess', { count: getSystemAccessPermissionsCount(user) })">
                      <i class="pi pi-eye"></i>
                      <span>{{ getSystemAccessPermissionsCount(user) }}/3</span>
                    </div>
                    <div class="permission-badge" [attr.data-level]="getPermissionLevel(getSystemConfigPermissionsCount(user), 5)"
                         [pTooltip]="t('permBadges.systemConfig', { count: getSystemConfigPermissionsCount(user) })">
                      <i class="pi pi-cog"></i>
                      <span>{{ getSystemConfigPermissionsCount(user) }}/5</span>
                    </div>
                    <div class="permission-badge" [attr.data-level]="getPermissionLevel(getMetadataEditingPermissionsCount(user), 7)"
                         [pTooltip]="t('permBadges.metadataEditing', { count: getMetadataEditingPermissionsCount(user) })">
                      <i class="pi pi-pencil"></i>
                      <span>{{ getMetadataEditingPermissionsCount(user) }}/7</span>
                    </div>
                    <div class="permission-badge" [attr.data-level]="getPermissionLevel(getDeviceSyncPermissionsCount(user), 3)"
                         [pTooltip]="t('permBadges.deviceSync', { count: getDeviceSyncPermissionsCount(user) })">
                      <i class="pi pi-mobile"></i>
                      <span>{{ getDeviceSyncPermissionsCount(user) }}/3</span>
                    </div>
                    <div class="permission-badge" [attr.data-level]="getPermissionLevel(getBulkResetPermissionsCount(user), 3)"
                         [pTooltip]="t('permBadges.bulkReset', { count: getBulkResetPermissionsCount(user) })">
                      <i class="pi pi-refresh"></i>
                      <span>{{ getBulkResetPermissionsCount(user) }}/3</span>
                    </div>
                  </div>
                </div>

                <div class="section-separator"></div>

                <div class="user-actions">
                  @if (!user.isEditing) {
                    <p-button
                      icon="pi pi-pencil"
                      severity="info"
                      size="small"
                      [outlined]="true"
                      [rounded]="true"
                      (onClick)="toggleEdit(user)"
                      [pTooltip]="t('actions.editUser')">
                    </p-button>
                    <p-button
                      icon="pi pi-key"
                      severity="warn"
                      size="small"
                      [outlined]="true"
                      [rounded]="true"
                      (onClick)="openChangePasswordDialog(user)"
                      [pTooltip]="t('actions.changePassword')">
                    </p-button>
                    <p-button
                      [disabled]="user.id === currentUser?.id"
                      icon="pi pi-trash"
                      severity="danger"
                      size="small"
                      [outlined]="true"
                      [rounded]="true"
                      (onClick)="deleteUser(user)"
                      [pTooltip]="t('actions.deleteUser')">
                    </p-button>
                  } @else {
                    <p-button
                      icon="pi pi-check"
                      severity="success"
                      size="small"
                      [outlined]="true"
                      [rounded]="true"
                      (onClick)="saveUser(user)"
                      [pTooltip]="t('actions.saveChanges')">
                    </p-button>
                    <p-button
                      icon="pi pi-times"
                      severity="secondary"
                      size="small"
                      [outlined]="true"
                      [rounded]="true"
                      (onClick)="toggleEdit(user)"
                      [pTooltip]="'common.cancel' | transloco">
                    </p-button>
                  }
                </div>
              </div>

              @if (isRowExpanded(user)) {
                <div class="user-card-body">
                  <div class="user-details-section">
                    <h4 class="details-title">
                      <i class="pi pi-id-card"></i>
                      {{ t('userInfo.title') }}
                    </h4>
                    <div class="details-grid">
                      <div class="detail-field">
                        <label>{{ t('userInfo.fullName') }}</label>
                        @if (user.isEditing) {
                          <input type="text" pInputText [(ngModel)]="user.name" [placeholder]="t('userInfo.enterFullName')"/>
                        } @else {
                          <span>{{ user.name || t('userInfo.notSet') }}</span>
                        }
                      </div>
                      <div class="detail-field">
                        <label>{{ t('userInfo.email') }}</label>
                        @if (user.isEditing) {
                          <input type="email" pInputText [(ngModel)]="user.email" [placeholder]="t('userInfo.enterEmail')"/>
                        } @else {
                          <span>{{ user.email || t('userInfo.notSet') }}</span>
                        }
                      </div>
                      <div class="detail-field detail-field-wide">
                        <label>{{ t('userInfo.libraries') }}</label>
                        @if (user.isEditing) {
                          <p-multiSelect
                            [options]="allLibraries"
                            optionLabel="name"
                            optionValue="id"
                            [(ngModel)]="editingLibraryIds"
                            [placeholder]="t('userInfo.selectLibraries')"
                            appendTo="body"
                            [disabled]="user.permissions.admin">
                          </p-multiSelect>
                        } @else {
                          <span>{{ user.libraryNames || t('userInfo.allLibrariesAdmin') }}</span>
                        }
                      </div>
                    </div>
                  </div>

                  <div class="permissions-section">
                    <h4 class="details-title">
                      <i class="pi pi-lock"></i>
                      {{ t('permissions') }}
                    </h4>

                    <div class="permissions-grid">
                      <div class="permission-group">
                        <h5>
                          <i class="pi pi-shield"></i>
                          {{ t('permGroups.administration') }}
                        </h5>
                        <div class="permission-items">
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.admin" (onChange)="onAdminCheckboxChange(user)" [disabled]="!user.isEditing" inputId="admin-{{user.id}}"></p-checkbox>
                            <label [for]="'admin-'+user.id">{{ t('perms.fullAdmin') }}</label>
                          </div>
                        </div>
                      </div>

                      <div class="permission-group">
                        <h5>
                          <i class="pi pi-book"></i>
                          {{ t('permGroups.bookManagement') }}
                        </h5>
                        <div class="permission-items">
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canUpload" [disabled]="isPermissionDisabled(user)" inputId="upload-{{user.id}}"></p-checkbox>
                            <label [for]="'upload-'+user.id">{{ t('perms.uploadBooks') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canDownload" [disabled]="isPermissionDisabled(user)" inputId="download-{{user.id}}"></p-checkbox>
                            <label [for]="'download-'+user.id">{{ t('perms.downloadBooks') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canDeleteBook" [disabled]="isPermissionDisabled(user)" inputId="delete-{{user.id}}"></p-checkbox>
                            <label [for]="'delete-'+user.id">{{ t('perms.deleteBooks') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canManageLibrary" [disabled]="isPermissionDisabled(user)" inputId="library-{{user.id}}"></p-checkbox>
                            <label [for]="'library-'+user.id">{{ t('perms.manageLibrary') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canEmailBook" [disabled]="isPermissionDisabled(user)" inputId="email-{{user.id}}"></p-checkbox>
                            <label [for]="'email-'+user.id">{{ t('perms.emailBooks') }}</label>
                          </div>
                        </div>
                      </div>

                      <div class="permission-group">
                        <h5>
                          <i class="pi pi-eye"></i>
                          {{ t('permGroups.systemAccess') }}
                        </h5>
                        <div class="permission-items">
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canAccessBookdrop" [disabled]="isPermissionDisabled(user)" inputId="bookdrop-{{user.id}}"></p-checkbox>
                            <label [for]="'bookdrop-'+user.id">{{ t('perms.accessBookdrop') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canAccessLibraryStats" [disabled]="isPermissionDisabled(user)" inputId="stats-{{user.id}}"></p-checkbox>
                            <label [for]="'stats-'+user.id">{{ t('perms.viewLibraryStats') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canAccessUserStats" [disabled]="isPermissionDisabled(user)" inputId="userstats-{{user.id}}"></p-checkbox>
                            <label [for]="'userstats-'+user.id">{{ t('perms.viewUserStats') }}</label>
                          </div>
                        </div>
                      </div>

                      <div class="permission-group">
                        <h5>
                          <i class="pi pi-cog"></i>
                          {{ t('permGroups.systemConfig') }}
                        </h5>
                        <div class="permission-items">
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canManageMetadataConfig" [disabled]="isPermissionDisabled(user)" inputId="metadataconfig-{{user.id}}"></p-checkbox>
                            <label [for]="'metadataconfig-'+user.id">{{ t('perms.manageMetadataConfig') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canManageGlobalPreferences" [disabled]="isPermissionDisabled(user)" inputId="preferences-{{user.id}}"></p-checkbox>
                            <label [for]="'preferences-'+user.id">{{ t('perms.manageAppPreferences') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canAccessTaskManager" [disabled]="isPermissionDisabled(user)" inputId="taskmanager-{{user.id}}"></p-checkbox>
                            <label [for]="'taskmanager-'+user.id">{{ t('perms.accessTaskManager') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canManageIcons" [disabled]="isPermissionDisabled(user)" inputId="icons-{{user.id}}"></p-checkbox>
                            <label [for]="'icons-'+user.id">{{ t('perms.manageIcons') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canManageFonts" [disabled]="isPermissionDisabled(user)" inputId="fonts-{{user.id}}"></p-checkbox>
                            <label [for]="'fonts-'+user.id">{{ t('perms.manageFonts') }}</label>
                          </div>
                        </div>
                      </div>

                      <div class="permission-group">
                        <h5>
                          <i class="pi pi-pencil"></i>
                          {{ t('permGroups.metadataEditing') }}
                        </h5>
                        <div class="permission-items">
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canEditMetadata" [disabled]="isPermissionDisabled(user)" inputId="metadata-{{user.id}}"></p-checkbox>
                            <label [for]="'metadata-'+user.id">{{ t('perms.editSingleMetadata') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canBulkAutoFetchMetadata" [disabled]="isPermissionDisabled(user)" inputId="bulkautofetch-{{user.id}}"></p-checkbox>
                            <label [for]="'bulkautofetch-'+user.id">{{ t('perms.bulkAutoFetch') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canBulkCustomFetchMetadata" [disabled]="isPermissionDisabled(user)" inputId="bulkcustomfetch-{{user.id}}"></p-checkbox>
                            <label [for]="'bulkcustomfetch-'+user.id">{{ t('perms.bulkCustomFetch') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canBulkEditMetadata" [disabled]="isPermissionDisabled(user)" inputId="bulkmetadataeditor-{{user.id}}"></p-checkbox>
                            <label [for]="'bulkmetadataeditor-'+user.id">{{ t('perms.accessBulkEditor') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canBulkRegenerateCover" [disabled]="isPermissionDisabled(user)" inputId="bulkregeneratecover-{{user.id}}"></p-checkbox>
                            <label [for]="'bulkregeneratecover-'+user.id">{{ t('perms.bulkRegenerateCover') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canMoveOrganizeFiles" [disabled]="isPermissionDisabled(user)" inputId="moveorganizefiles-{{user.id}}"></p-checkbox>
                            <label [for]="'moveorganizefiles-'+user.id">{{ t('perms.moveOrganize') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canBulkLockUnlockMetadata" [disabled]="isPermissionDisabled(user)" inputId="bulklockunlock-{{user.id}}"></p-checkbox>
                            <label [for]="'bulklockunlock-'+user.id">{{ t('perms.bulkLockUnlock') }}</label>
                          </div>
                        </div>
                      </div>

                      <div class="permission-group">
                        <h5>
                          <i class="pi pi-mobile"></i>
                          {{ t('permGroups.deviceSync') }}
                        </h5>
                        <div class="permission-items">
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canSyncKoReader" [disabled]="isPermissionDisabled(user)" inputId="koreader-{{user.id}}"></p-checkbox>
                            <label [for]="'koreader-'+user.id">{{ t('perms.koreaderSync') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canSyncKobo" [disabled]="isPermissionDisabled(user)" inputId="kobo-{{user.id}}"></p-checkbox>
                            <label [for]="'kobo-'+user.id">{{ t('perms.koboSync') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canAccessOpds" [disabled]="isPermissionDisabled(user)" inputId="opds-{{user.id}}"></p-checkbox>
                            <label [for]="'opds-'+user.id">{{ t('perms.opdsFeedAccess') }}</label>
                          </div>
                        </div>
                      </div>

                      <div class="permission-group">
                        <h5>
                          <i class="pi pi-refresh"></i>
                          {{ t('permGroups.bulkReset') }}
                        </h5>
                        <div class="permission-items">
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canBulkResetBookloreReadProgress" [disabled]="isPermissionDisabled(user)" inputId="bulkresetbooklore-{{user.id}}"></p-checkbox>
                            <label [for]="'bulkresetbooklore-'+user.id">{{ t('perms.bulkResetBooklore') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canBulkResetKoReaderReadProgress" [disabled]="isPermissionDisabled(user)" inputId="bulkresetkoreader-{{user.id}}"></p-checkbox>
                            <label [for]="'bulkresetkoreader-'+user.id">{{ t('perms.bulkResetKoreader') }}</label>
                          </div>
                          <div class="permission-item">
                            <p-checkbox [binary]="true" [(ngModel)]="user.permissions.canBulkResetBookReadStatus" [disabled]="isPermissionDisabled(user)" inputId="bulkresetreadstatus-{{user.id}}"></p-checkbox>
                            <label [for]="'bulkresetreadstatus-'+user.id">{{ t('perms.bulkResetReadStatus') }}</label>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="content-restrictions-section">
                    <h4 class="details-title">
                      <i class="pi pi-eye-slash"></i>
                      {{ t('contentRestrictions.title') }}
                    </h4>
                    <p class="section-description">
                      {{ t('contentRestrictions.description') }}
                    </p>
                    <app-content-restrictions-editor
                      [userId]="user.id"
                      [isEditing]="user.isEditing ?? false">
                    </app-content-restrictions-editor>
                  </div>
                </div>
              }
            </div>
          }
        </div>
      }
    </div>
  </div>

  <p-dialog
    [header]="t('passwordDialog.title')"
    [(visible)]="isPasswordDialogVisible"
    [modal]="true"
    class="user-dialog"
    [style]="{width: '400px'}">
    <div class="dialog-form">
      <div class="form-field">
        <label for="newPassword">{{ t('passwordDialog.newPassword') }}</label>
        <p-password
          id="newPassword"
          [(ngModel)]="newPassword"
          [placeholder]="t('passwordDialog.enterNew')"
          [feedback]="false"
          fluid>
        </p-password>
      </div>
      <div class="form-field">
        <label for="confirmPassword">{{ t('passwordDialog.confirmPassword') }}</label>
        <p-password
          id="confirmPassword"
          [(ngModel)]="confirmNewPassword"
          [placeholder]="t('passwordDialog.confirmNew')"
          [feedback]="false"
          fluid>
        </p-password>
      </div>
      @if (passwordError) {
        <div class="error-message">
          <i class="pi pi-exclamation-triangle"></i>
          <span>{{ passwordError }}</span>
        </div>
      }
    </div>
    <ng-template pTemplate="footer">
      <div class="dialog-actions">
        <p-button
          [label]="'common.cancel' | transloco"
          severity="secondary"
          outlined="true"
          (onClick)="isPasswordDialogVisible = false">
        </p-button>
        <p-button
          [label]="t('passwordDialog.changeBtn')"
          severity="success"
          (onClick)="submitPasswordChange()">
        </p-button>
      </div>
    </ng-template>
  </p-dialog>
</div>
</ng-container>
