<div class="flex flex-col gap-2 min-h-screen">
  <div class="flex items-center justify-between">
    <h2 class="text-2xl font-semibold">Gestion des Agents</h2>
    <z-button (click)="openCreate()">Nouvel agent</z-button>
  </div>

  <app-search-bar (search)="onSearch($event)"></app-search-bar>

  <app-data-table [data]="rows()" [columns]="cols" [sort]="sort()" (sortChange)="sort.set($event)">
    <ng-template #rowActions let-row>
      <div class="flex gap-3">
        <button z-button zType="ghost" (click)="openDetail(row)" title="Voir les détails">
          <i class="icon-eye"></i>
        </button>
        <button z-button zType="ghost" (click)="openAssignTpe(row)" title="Assigner un TPE">
          <i class="icon-plus"></i>
        </button>
        <button z-button zType="ghost" (click)="openEdit(row)" title="Modifier">
          <i class="icon-pen"></i>
        </button>
        <button z-button zType="destructive" (click)="remove(row)" title="Supprimer">
          <i class="icon-trash"></i>
        </button>
      </div>
    </ng-template>
  </app-data-table>

  <app-paginator
    [total]="total()"
    [page]="page()"
    [perPage]="size()"
    (pageChange)="page.set($event)"
    (perPageChange)="size.set($event)"
  ></app-paginator>
</div>

<app-modal [open]="modalOpen()" [title]="modalTitle()" (close)="closeModal()" size="xxl">
  <app-agent-full-form
    [value]="editingItem() ?? undefined"
    (save)="onFormSave($event)"
    (cancel)="closeModal()"
  />
  <div modal-actions class="flex justify-end gap-2">
    <z-button zType="destructive" (click)="closeModal()">Annuler</z-button>
    <z-button (click)="submitChildForm()">Enregistrer</z-button>
  </div>
</app-modal>

<!-- Detail Modal -->
@if (detailItem()) {
<app-modal [open]="detailModalOpen()" [title]="'Détails de l\'agent'" (close)="closeDetailModal()" size="xxl">
  @if (detailItem(); as agent) {
  <div class="space-y-6">
    <!-- Informations Emploi -->
    <z-card class="p-4">
      <div class="text-lg font-semibold mb-4">Informations Emploi</div>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div>
          <div class="text-xs text-muted-foreground mb-1">Code</div>
          <div class="font-medium">{{ agent.code }}</div>
        </div>
        <div>
          <div class="text-xs text-muted-foreground mb-1">Profil</div>
          <div class="font-medium">{{ agent.profile }}</div>
        </div>
        <div>
          <div class="text-xs text-muted-foreground mb-1">Statut</div>
          <div class="font-medium">
            @if (agent.statut === 'ACTIF') {
            <span class="inline-flex items-center gap-1 px-2 py-1 rounded bg-green-500/10 text-green-600 dark:text-green-400 text-xs font-medium">
              <i class="icon-check"></i> Actif
            </span>
            } @else if (agent.statut === 'INACTIF') {
            <span class="inline-flex items-center gap-1 px-2 py-1 rounded bg-gray-500/10 text-gray-600 dark:text-gray-400 text-xs font-medium">
              <i class="icon-x"></i> Inactif
            </span>
            } @else {
            <span class="inline-flex items-center gap-1 px-2 py-1 rounded bg-orange-500/10 text-orange-600 dark:text-orange-400 text-xs font-medium">
              <i class="icon-alert-circle"></i> Suspendu
            </span>
            }
          </div>
        </div>
        @if (agent.principalCode) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Agent Principal</div>
          <div class="font-medium">{{ agent.principalCode }}</div>
        </div>
        }
        @if (agent.zone) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Zone</div>
          <div class="font-medium">{{ agent.zone }}</div>
        </div>
        }
        @if (agent.kiosk) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Kiosque</div>
          <div class="font-medium">{{ agent.kiosk }}</div>
        </div>
        }
        @if (agent.fonction) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Fonction</div>
          <div class="font-medium">{{ agent.fonction }}</div>
        </div>
        }
        @if (agent.dateEmbauche) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Date Embauche</div>
          <div class="font-medium">{{ agent.dateEmbauche | date: 'dd/MM/yyyy' }}</div>
        </div>
        }
      </div>
    </z-card>

    <!-- Informations Personnelles -->
    <z-card class="p-4">
      <div class="text-lg font-semibold mb-4">Informations Personnelles</div>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div>
          <div class="text-xs text-muted-foreground mb-1">Nom</div>
          <div class="font-medium">{{ agent.nom }}</div>
        </div>
        <div>
          <div class="text-xs text-muted-foreground mb-1">Prénom</div>
          <div class="font-medium">{{ agent.prenom }}</div>
        </div>
        @if (agent.autresNoms) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Autre(s) Nom(s)</div>
          <div class="font-medium">{{ agent.autresNoms }}</div>
        </div>
        }
        @if (agent.dateNaissance) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Date de naissance</div>
          <div class="font-medium">{{ agent.dateNaissance | date: 'dd/MM/yyyy' }}</div>
        </div>
        }
        @if (agent.lieuNaissance) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Lieu de naissance</div>
          <div class="font-medium">{{ agent.lieuNaissance }}</div>
        </div>
        }
        @if (agent.ville) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Ville</div>
          <div class="font-medium">{{ agent.ville }}</div>
        </div>
        }
        @if (agent.adresse) {
        <div class="md:col-span-2">
          <div class="text-xs text-muted-foreground mb-1">Adresse</div>
          <div class="font-medium">{{ agent.adresse }}</div>
        </div>
        }
        @if (agent.phone) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Téléphone</div>
          <div class="font-medium">{{ agent.phone }}</div>
        </div>
        }
        @if (agent.autoriserAides !== undefined) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Autoriser Aides</div>
          <div class="font-medium">
            @if (agent.autoriserAides) {
            <span class="text-green-600 dark:text-green-400">Oui</span>
            } @else {
            <span class="text-gray-600 dark:text-gray-400">Non</span>
            }
          </div>
        </div>
        }
      </div>
    </z-card>

    <!-- Limites et Configuration -->
    <z-card class="p-4">
      <div class="text-lg font-semibold mb-4">Limites et Configuration</div>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        @if (agent.limiteInferieure !== undefined) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Limite inférieure</div>
          <div class="font-medium">{{ agent.limiteInferieure | number: '1.2-2' }}</div>
        </div>
        }
        @if (agent.limiteSuperieure !== undefined) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Limite supérieure</div>
          <div class="font-medium">{{ agent.limiteSuperieure | number: '1.2-2' }}</div>
        </div>
        }
        @if (agent.limiteParTransaction !== undefined) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Limite / transaction</div>
          <div class="font-medium">{{ agent.limiteParTransaction | number: '1.2-2' }}</div>
        </div>
        }
        @if (agent.limiteMinAirtime !== undefined) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Limite min airtime</div>
          <div class="font-medium">{{ agent.limiteMinAirtime | number: '1.2-2' }}</div>
        </div>
        }
        @if (agent.limiteMaxAirtime !== undefined) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Limite max airtime</div>
          <div class="font-medium">{{ agent.limiteMaxAirtime | number: '1.2-2' }}</div>
        </div>
        }
        @if (agent.maxPeripheriques !== undefined) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Nbre max. périphériques</div>
          <div class="font-medium">{{ agent.maxPeripheriques }}</div>
        </div>
        }
      </div>
    </z-card>

    <!-- Informations Légales -->
    @if (agent.nationalite || agent.cni || agent.cniDelivreeLe || agent.residence || agent.statutMarital) {
    <z-card class="p-4">
      <div class="text-lg font-semibold mb-4">Informations Légales</div>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        @if (agent.nationalite) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Nationalité</div>
          <div class="font-medium">{{ agent.nationalite }}</div>
        </div>
        }
        @if (agent.cni) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">N° CNI</div>
          <div class="font-medium">{{ agent.cni }}</div>
        </div>
        }
        @if (agent.cniDelivreeLe) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">CNI Délivrée le</div>
          <div class="font-medium">{{ agent.cniDelivreeLe | date: 'dd/MM/yyyy' }}</div>
        </div>
        }
        @if (agent.cniDelivreeA) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">CNI Délivrée à</div>
          <div class="font-medium">{{ agent.cniDelivreeA }}</div>
        </div>
        }
        @if (agent.residence) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Résidence</div>
          <div class="font-medium">{{ agent.residence }}</div>
        </div>
        }
        @if (agent.statutMarital) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Statut marital</div>
          <div class="font-medium">{{ agent.statutMarital }}</div>
        </div>
        }
        @if (agent.epoux) {
        <div>
          <div class="text-xs text-muted-foreground mb-1">Époux/Épouse</div>
          <div class="font-medium">{{ agent.epoux }}</div>
        </div>
        }
      </div>
    </z-card>
    }

    <!-- Membres de famille -->
    @if (detailFamilyMembers().length > 0) {
    <z-card class="p-4">
      <div class="text-lg font-semibold mb-4">Membres de famille</div>
      <div class="space-y-3">
        @for (member of detailFamilyMembers(); track member.id || $index) {
        <div class="border rounded-lg p-3 bg-surface/50">
          <div class="flex items-start justify-between">
            <div class="flex-1 grid grid-cols-1 md:grid-cols-4 gap-3">
              <div>
                <div class="text-xs text-muted-foreground mb-1">Nom</div>
                <div class="font-medium">{{ member.nom }}</div>
              </div>
              @if (member.statut) {
              <div>
                <div class="text-xs text-muted-foreground mb-1">Statut</div>
                <div class="font-medium">{{ member.statut }}</div>
              </div>
              }
              @if (member.dateNaissance) {
              <div>
                <div class="text-xs text-muted-foreground mb-1">Date de naissance</div>
                <div class="font-medium">{{ member.dateNaissance | date: 'dd/MM/yyyy' }}</div>
              </div>
              }
              @if (member.sexe) {
              <div>
                <div class="text-xs text-muted-foreground mb-1">Sexe</div>
                <div class="font-medium">{{ member.sexe === 'M' ? 'Masculin' : 'Féminin' }}</div>
              </div>
              }
            </div>
          </div>
        </div>
        }
      </div>
    </z-card>
    }

    <!-- TPE Assignés -->
    @if (getAgentTpes(agent.id).length > 0) {
    <z-card class="p-4">
      <div class="text-lg font-semibold mb-4">TPE Assignés ({{ getAgentTpes(agent.id).length }})</div>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
        @for (tpe of getAgentTpes(agent.id); track tpe.id) {
        <div class="px-3 py-2.5 rounded bg-primary/10 border border-primary/20">
          <div class="flex items-start justify-between mb-2">
            <div class="font-medium text-sm">{{ tpe.imei }}</div>
            @if (tpe.statut) {
            <span class="text-xs px-2 py-0.5 rounded bg-surface text-muted-foreground">
              {{ formatTpeStatut(tpe.statut) }}
            </span>
            }
          </div>
          <div class="space-y-1 text-xs text-muted-foreground">
            @if (tpe.marque || tpe.modele) {
            <div>
              <span class="font-medium">Modèle:</span> {{ tpe.marque }} {{ tpe.modele }}
            </div>
            }
            @if (tpe.serial) {
            <div>
              <span class="font-medium">Série:</span> {{ tpe.serial }}
            </div>
            }
            @if (tpe.type) {
            <div>
              <span class="font-medium">Type:</span> {{ tpe.type }}
            </div>
            }
          </div>
        </div>
        }
      </div>
    </z-card>
    }
  </div>
  }
  <div modal-actions class="flex justify-end gap-2">
    <z-button zType="default" (click)="closeDetailModal()">Fermer</z-button>
    @if (detailItem()) {
    <z-button zType="default" (click)="openEdit(detailItem()!); closeDetailModal()">
      <i class="icon-pen mr-2"></i>Modifier
    </z-button>
    }
  </div>
</app-modal>
}

<!-- TPE Assignment Modal -->
@if (assigningAgent()) {
<app-modal
  [open]="assignTpeModalOpen()"
  [title]="'Assigner un TPE à ' + (assigningAgent()?.nom || '') + ' ' + (assigningAgent()?.prenom || '')"
  (close)="closeAssignTpeModal()"
  size="md"
>
  <div class="space-y-4">
    @if (tpesLoading()) {
    <div class="text-center py-4">Chargement des TPE disponibles...</div>
    } @else if (availableTpes().length === 0) {
    <div class="text-center py-4 text-muted-foreground">Aucun TPE disponible</div>
    } @else {
    <z-form-field>
      <label z-form-label>Sélectionner un TPE</label>
      <div z-form-control>
        <z-select
          [zValue]="selectedTpeId()"
          (zSelectionChange)="selectedTpeId.set($event)"
          [zPlaceholder]="'Sélectionner un TPE...'"
        >
          @for (tpe of availableTpes(); track tpe.id) {
          <z-select-item [zValue]="tpe.id">
            {{ tpe.imei }} - {{ tpe.marque }} {{ tpe.modele }}
            @if (tpe.statut === 'VALIDE') {
            <span class="text-xs text-green-600 dark:text-green-400 ml-2">(Valide)</span>
            }
          </z-select-item>
          }
        </z-select>
      </div>
    </z-form-field>
    }
  </div>
  <div modal-actions class="flex justify-end gap-2">
    <z-button zType="destructive" (click)="closeAssignTpeModal()">Annuler</z-button>
    <button z-button [disabled]="!selectedTpeId() || tpesLoading()" (click)="confirmAssignTpe()">
      Assigner
    </button>
  </div>
</app-modal>
}
