<div class="container-fluid">
  <!-- En-tête avec navigation -->
  <div class="row mb-4">
    <div class="col-12">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h4 class="mb-1">
            @if (subscription) {
              Paiements - Abonnement #{{ subscription.id }}
            } @else {
              Paiements de l'Abonnement
            }
          </h4>
          <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0">
              <li class="breadcrumb-item">
                <a href="javascript:void(0)" (click)="goBack()" class="text-decoration-none cursor-pointer">
                  Abonnements
                </a>
              </li>
              <li class="breadcrumb-item active" aria-current="page">
                @if (subscription) {
                  Paiements #{{ subscription.id }}
                } @else {
                  Paiements
                }
              </li>
            </ol>
          </nav>
        </div>
        
        <div class="d-flex gap-2">
          <!-- Bouton d'actualisation -->
          <button 
            class="btn btn-outline-secondary"
            (click)="refresh()"
            [disabled]="loading || loadingPayments"
          >
            <ng-icon name="lucideRefreshCw" class="me-1" [class.spin]="loading || loadingPayments"></ng-icon>
            Actualiser
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Messages d'alerte -->
  @if (error) {
    <div class="alert alert-danger">
      <div class="d-flex align-items-center">
        <ng-icon name="lucideAlertCircle" class="me-2"></ng-icon>
        <div>{{ error }}</div>
        <button class="btn-close ms-auto" (click)="clearMessages()"></button>
      </div>
    </div>
  }

  @if (success) {
    <div class="alert alert-success">
      <div class="d-flex align-items-center">
        <ng-icon name="lucideCheckCircle" class="me-2"></ng-icon>
        <div>{{ success }}</div>
        <button class="btn-close ms-auto" (click)="clearMessages()"></button>
      </div>
    </div>
  }

  <div class="row">
    <!-- Loading State -->
    @if (loading) {
      <div class="col-12 text-center py-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">Chargement...</span>
        </div>
        <p class="mt-2 text-muted">Chargement des détails de l'abonnement...</p>
      </div>
    }

    <!-- Subscription Details & Payments -->
    @if (subscription && !loading) {
      <!-- Colonne de gauche - Informations de l'abonnement -->
      <div class="col-xl-4 col-lg-5">
        <!-- Carte abonnement -->
        <div class="card">
          <div class="card-header bg-light">
            <h5 class="card-title mb-0">Détails de l'Abonnement</h5>
          </div>
          <div class="card-body text-center">
            <!-- Icône abonnement -->
            <div class="avatar-lg mx-auto mb-3">
              <div class="avatar-title bg-primary bg-opacity-10 rounded-circle text-primary fs-24">
                <ng-icon name="lucideRepeat"></ng-icon>
              </div>
            </div>
            
            <h5>Abonnement #{{ subscription.id }}</h5>
            <p class="text-muted mb-2">{{ subscription.token.substring(0, 20) }}...</p>
            
            <!-- Statut -->
            <span [class]="getStatusBadgeClass(subscription.status)" class="mb-3 d-block">
              <ng-icon 
                [name]="subscription.status === SubscriptionStatus.ACTIVE ? 'lucideCheckCircle' : 
                        subscription.status === SubscriptionStatus.SUSPENDED ? 'lucidePauseCircle' :
                        subscription.status === SubscriptionStatus.CANCELLED ? 'lucideXCircle' : 'lucideClock'"
                class="me-1" 
              ></ng-icon>
              {{ getStatusDisplayName(subscription.status) }}
            </span>

            <!-- Indicateur de santé -->
            <div class="mb-3">
              <small class="d-flex align-items-center justify-content-center" [ngClass]="getSubscriptionHealthColor()">
                <ng-icon [name]="getSubscriptionHealthIcon()" class="me-1"></ng-icon>
                @switch (getSubscriptionHealth()) {
                  @case ('good') { Bon état }
                  @case ('warning') { Attention nécessaire }
                  @case ('danger') { Problème détecté }
                }
              </small>
            </div>

            <!-- Informations rapides -->
            <div class="mt-4 text-start">
              <div class="d-flex align-items-center mb-2">
                <ng-icon name="lucideDollarSign" class="me-2 text-muted"></ng-icon>
                <small>{{ formatAmount(subscription.amount, subscription.currency) }}</small>
              </div>
              <div class="d-flex align-items-center mb-2">
                <ng-icon name="lucideCalendar" class="me-2 text-muted"></ng-icon>
                <small>{{ getPeriodicityDisplayName(subscription.periodicity) }}</small>
              </div>
              <div class="d-flex align-items-center mb-2">
                <ng-icon name="lucidePlay" class="me-2 text-muted"></ng-icon>
                <small>Début : {{ formatDate(subscription.startDate) }}</small>
              </div>
              <div class="d-flex align-items-center mb-2">
                <ng-icon name="lucideCalendar" class="me-2 text-muted"></ng-icon>
                <small>Prochain : {{ formatDate(subscription.nextPaymentDate) }}</small>
              </div>
              @if (subscription.endDate) {
                <div class="d-flex align-items-center">
                  <ng-icon name="lucideFlag" class="me-2 text-muted"></ng-icon>
                  <small>Fin : {{ formatDate(subscription.endDate) }}</small>
                </div>
              }
            </div>
          </div>
        </div>

        <!-- Carte statistiques -->
        <div class="card mt-3">
          <div class="card-header bg-light">
            <h5 class="card-title mb-0">Statistiques des Paiements</h5>
          </div>
          <div class="card-body">
            <div class="row text-center">
              <div class="col-6 mb-3">
                <div class="text-primary fw-bold fs-4">{{ getTotalPayments() }}</div>
                <small class="text-muted">Total</small>
              </div>
              <div class="col-6 mb-3">
                <div class="text-success fw-bold fs-4">{{ getSuccessfulPayments() }}</div>
                <small class="text-muted">Réussis</small>
              </div>
              <div class="col-6">
                <div class="text-danger fw-bold fs-4">{{ getFailedPayments() }}</div>
                <small class="text-muted">Échoués</small>
              </div>
              <div class="col-6">
                <div class="text-warning fw-bold fs-4">{{ getPendingPayments() }}</div>
                <small class="text-muted">En attente</small>
              </div>
            </div>
            <hr>
            <div class="text-center">
              <div class="fw-bold fs-5">{{ formatAmount(getTotalAmount(), subscription.currency) }}</div>
              <small class="text-muted">Montant total collecté</small>
            </div>
            <div class="text-center mt-2">
              <div class="fw-bold fs-6">{{ getSuccessRate().toFixed(1) }}%</div>
              <small class="text-muted">Taux de réussite</small>
            </div>
          </div>
        </div>

        <!-- Informations techniques -->
        <div class="card mt-3">
          <div class="card-header bg-light">
            <h6 class="card-title mb-0">Informations Techniques</h6>
          </div>
          <div class="card-body">
            <div class="row g-2 small">
              <div class="col-12">
                <strong>ID Abonnement :</strong>
                <div class="text-muted font-monospace">{{ subscription.id }}</div>
              </div>
              <div class="col-12">
                <strong>Token :</strong>
                <div class="text-muted font-monospace text-truncate">{{ subscription.token }}</div>
              </div>
              <div class="col-12">
                <strong>Merchant ID :</strong>
                <div class="text-muted">{{ subscription.merchantPartnerId }}</div>
              </div>
              <div class="col-12">
                <strong>Client ID :</strong>
                <div class="text-muted">{{ subscription.customerId }}</div>
              </div>
              <div class="col-12">
                <strong>Échecs :</strong>
                <div class="text-muted">{{ subscription.failureCount }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Colonne de droite - Historique des paiements -->
      <div class="col-xl-8 col-lg-7">
        <!-- Filtres -->
        <div class="card mb-3">
          <div class="card-header bg-light">
            <h5 class="card-title mb-0">Filtres des Paiements</h5>
          </div>
          <div class="card-body">
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">Statut</label>
                <select class="form-select" [(ngModel)]="statusFilter" (change)="applyFilters()">
                  <option value="all">Tous les statuts</option>
                  <option value="SUCCESS">Réussis</option>
                  <option value="FAILED">Échoués</option>
                  <option value="PENDING">En attente</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Période</label>
                <select class="form-select" [(ngModel)]="dateFilter" (change)="applyFilters()">
                  <option value="all">Toute période</option>
                  <option value="week">7 derniers jours</option>
                  <option value="month">30 derniers jours</option>
                  <option value="quarter">3 derniers mois</option>
                </select>
              </div>
              <div class="col-12">
                <button class="btn btn-outline-secondary btn-sm" (click)="clearFilters()">
                  <ng-icon name="lucideX" class="me-1"></ng-icon>
                  Réinitialiser les filtres
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Liste des paiements -->
        <div class="card">
          <div class="card-header bg-light d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">
              <ng-icon name="lucideCreditCard" class="me-2"></ng-icon>
              Historique des Paiements
              <span class="badge bg-primary ms-2">{{ getSortedPayments().length }}</span>
            </h5>
          </div>

          <div class="card-body">
            <!-- Loading State Payments -->
            @if (loadingPayments) {
              <div class="text-center py-4">
                <div class="spinner-border spinner-border-sm text-primary" role="status">
                  <span class="visually-hidden">Chargement...</span>
                </div>
                <p class="mt-2 text-muted">Chargement des paiements...</p>
              </div>
            }

            <!-- Payments List -->
            @if (!loadingPayments) {
              <div class="table-responsive">
                <table class="table table-hover table-sm">
                  <thead class="table-light">
                    <tr>
                      <th>Référence</th>
                      <th>Date</th>
                      <th>Montant</th>
                      <th>Statut</th>
                      <th>Description</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    @for (payment of getSortedPayments(); track payment.id) {
                      <tr>
                        <td>
                          <code class="small" [title]="payment.reference">
                            {{ payment.reference.substring(0, 12) }}...
                          </code>
                        </td>
                        <td>
                          <small>{{ formatDateTime(payment.createdAt) }}</small>
                        </td>
                        <td>
                          <strong>{{ formatAmount(payment.amount, payment.currency) }}</strong>
                        </td>
                        <td>
                          <span class="badge d-flex align-items-center" [ngClass]="getPaymentStatusBadgeClass(payment.status)">
                            <ng-icon 
                              [name]="payment.status === 'SUCCESS' ? 'lucideCheckCircle' : 
                                      payment.status === 'FAILED' ? 'lucideXCircle' : 'lucideClock'"
                              class="me-1" 
                              size="12"
                            ></ng-icon>
                            {{ getPaymentStatusDisplayName(payment.status) }}
                          </span>
                        </td>
                        <td>
                          <small class="text-muted">{{ payment.description }}</small>
                          @if (payment.metadata.internatRef) {
                            <br>
                            <small class="text-muted">
                              Ref: {{ payment.metadata.internatRef }}
                            </small>
                          }
                        </td>
                        <td>
                          <button class="btn btn-outline-primary btn-sm" title="Voir détails">
                            <ng-icon name="lucideEye"></ng-icon>
                          </button>
                        </td>
                      </tr>
                    }
                    @empty {
                      <tr>
                        <td colspan="6" class="text-center py-4">
                          <div class="text-muted">
                            <ng-icon name="lucideCreditCard" class="fs-1 mb-3 opacity-50"></ng-icon>
                            <h5 class="mb-2">Aucun paiement trouvé</h5>
                            <p class="mb-3">Aucun paiement ne correspond à vos critères de filtrage.</p>
                          </div>
                        </td>
                      </tr>
                    }
                  </tbody>
                </table>
              </div>

              <!-- Résumé des résultats filtrés -->
              @if (getSortedPayments().length > 0) {
                <div class="mt-3 pt-3 border-top">
                  <div class="row text-center small">
                    <div class="col">
                      <span class="text-muted">
                        Affichage de {{ getSortedPayments().length }} paiement(s)
                      </span>
                    </div>
                    @if (statusFilter !== 'all') {
                      <div class="col">
                        <span class="text-muted">
                          Filtre : {{ 
                            statusFilter === 'SUCCESS' ? 'Réussis' :
                            statusFilter === 'FAILED' ? 'Échoués' : 'En attente'
                          }}
                        </span>
                      </div>
                    }
                  </div>
                </div>
              }
            }
          </div>
        </div>

        <!-- Alertes et indicateurs -->
        @if (isExpiringSoon()) {
          <div class="alert alert-warning mt-3">
            <div class="d-flex align-items-center">
              <ng-icon name="lucideAlertTriangle" class="me-2"></ng-icon>
              <div>
                <strong>Attention :</strong> Cet abonnement expire bientôt
              </div>
            </div>
          </div>
        }

        @if (isExpired()) {
          <div class="alert alert-danger mt-3">
            <div class="d-flex align-items-center">
              <ng-icon name="lucideXCircle" class="me-2"></ng-icon>
              <div>
                <strong>Expiré :</strong> Cet abonnement a expiré
              </div>
            </div>
          </div>
        }

        @if (getDaysUntilNextPayment() <= 3 && subscription.status === SubscriptionStatus.ACTIVE) {
          <div class="alert alert-info mt-3">
            <div class="d-flex align-items-center">
              <ng-icon name="lucideCalendar" class="me-2"></ng-icon>
              <div>
                <strong>Prochain paiement :</strong> Dans {{ getDaysUntilNextPayment() }} jour(s)
              </div>
            </div>
          </div>
        }
      </div>
    }
  </div>
</div>