import { Component, inject, OnInit, TemplateRef, ViewChild, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgIcon } from '@ng-icons/core';
import { NgbNavModule, NgbModal, NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
import { catchError, map, of, Subject, takeUntil } from 'rxjs';

import { SubscriptionsService } from './subscriptions.service';
import { AuthService } from '@core/services/auth.service';
import { PageTitle } from '@app/components/page-title/page-title';
import { SubscriptionsList } from './subscriptions-list/subscriptions-list';
import { SubscriptionPayments } from './subscription-payments/subscription-payments';

import { 
  Subscription,
  SubscriptionPayment,
  SubscriptionStatus,
  SubscriptionPeriodicity,
  Currency
} from '@core/models/dcb-bo-hub-subscription.model';
import { User, UserRole } from '@core/models/dcb-bo-hub-user.model';
import { RoleManagementService } from '@core/services/hub-users-roles-management.service';

@Component({
  selector: 'app-subscriptions',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    NgIcon,
    NgbNavModule,
    NgbModalModule,
    PageTitle,
    SubscriptionsList,
    SubscriptionPayments
  ],
  templateUrl: './subscriptions.html',
})
export class SubscriptionsManagement implements OnInit, OnDestroy {
  private authService = inject(AuthService);
  private subscriptionsService = inject(SubscriptionsService);
  private roleService = inject(RoleManagementService);
  
  private cdRef = inject(ChangeDetectorRef);
  private destroy$ = new Subject<void>();

  // Configuration
  readonly SubscriptionStatus = SubscriptionStatus;
  readonly SubscriptionPeriodicity = SubscriptionPeriodicity;
  readonly Currency = Currency;
  
  // Propriétés de configuration
  pageTitle: string = 'Gestion des Abonnements';
  badge: any = { icon: 'lucideRepeat', text: 'Abonnements' };

  // État de l'interface
  activeTab: 'list' | 'payments' = 'list';
  selectedSubscriptionId: string | null = null;

  user: User | undefined;
  
  // Gestion des rôles (lecture seule)
  availableRoles: { value: UserRole; label: string; description: string }[] = [];

  // Gestion des permissions
  currentUserRole: string | null = null;
  currentMerchantPartnerId: string = '';

  // Données
  subscriptionPayments: { [subscriptionId: string]: SubscriptionPayment[] } = {};
  selectedSubscriptionForPayments: Subscription | null = null;

  // Références aux composants enfants
  @ViewChild(SubscriptionsList) subscriptionsList!: SubscriptionsList;

  ngOnInit() {
    this.activeTab = 'list';
    this.loadCurrentUserPermissions();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  /**
   * Initialise les permissions de l'utilisateur courant
   */
  private loadCurrentUserPermissions(): void {
    this.authService.getUserProfile()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (user) => {
          this.currentUserRole = this.extractUserRole(user);
          this.currentMerchantPartnerId = this.extractMerchantPartnerId(user);

          console.log(`User ROLE: ${this.currentUserRole}`);
          console.log(`Merchant Partner ID: ${this.currentMerchantPartnerId}`);
        },
        error: (error) => {
          console.error('Error loading user profile:', error);
          this.fallbackPermissions();
        }
      });
  }

  /**
   * Extraire le rôle de l'utilisateur
   */
  private extractUserRole(user: any): string | null {
    const userRoles = this.authService.getCurrentUserRoles();
    if (userRoles && userRoles.length > 0) {
      return userRoles[0];
    }
    return null;
  }

  /**
   * Extraire le merchantPartnerId
   */
  private extractMerchantPartnerId(user: any): string {
    if (user?.merchantPartnerId) {
      return user.merchantPartnerId;
    }
    return this.authService.getCurrentMerchantPartnerId() || '';
  }

  /**
   * Fallback en cas d'erreur de chargement du profil
   */
  private fallbackPermissions(): void {
    this.currentUserRole = this.authService.getCurrentUserRole();
    this.currentMerchantPartnerId = this.authService.getCurrentMerchantPartnerId() || '';
  }

  // ==================== MÉTHODES D'INTERFACE ====================

  // Méthode pour changer d'onglet
  showTab(tab: 'list' | 'payments', subscriptionId?: string) {
    console.log(`Switching to tab: ${tab}`, subscriptionId ? `for subscription ${subscriptionId}` : '');
    this.activeTab = tab;
    
    if (subscriptionId) {
      this.selectedSubscriptionId = subscriptionId;
    }
  }

  backToList() {
    console.log('🔙 Returning to list view');
    this.activeTab = 'list';
    this.selectedSubscriptionId = null;
  }

  // Méthodes de gestion des événements du composant enfant
  onSubscriptionSelected(subscriptionId: string) {
    this.showTab('payments', subscriptionId);
  }

  onViewPaymentsRequested(subscriptionId: string) {
    this.showTab('payments', subscriptionId);
  }

  // ==================== MÉTHODES UTILITAIRES ====================

  private refreshSubscriptionsList(): void {
    if (this.subscriptionsList && typeof this.subscriptionsList.refreshData === 'function') {
      console.log('🔄 Refreshing subscriptions list...');
      this.subscriptionsList.refreshData();
    } else {
      console.warn('❌ SubscriptionsList component not available for refresh');
      this.showTab('list');
    }
  }

  // Méthodes pour les templates
  getStatusDisplayName(status: SubscriptionStatus): string {
    const statusNames: { [key: string]: string } = {
      [SubscriptionStatus.ACTIVE]: 'Actif',
      [SubscriptionStatus.SUSPENDED]: 'Suspendu',
      [SubscriptionStatus.CANCELLED]: 'Annulé',
      [SubscriptionStatus.EXPIRED]: 'Expiré',
      [SubscriptionStatus.PENDING]: 'En attente'
    };
    return statusNames[status] || status;
  }

  getPeriodicityDisplayName(periodicity: SubscriptionPeriodicity): string {
    const periodicityNames: { [key: string]: string } = {
      [SubscriptionPeriodicity.DAILY]: 'Quotidien',
      [SubscriptionPeriodicity.WEEKLY]: 'Hebdomadaire',
      [SubscriptionPeriodicity.MONTHLY]: 'Mensuel',
      [SubscriptionPeriodicity.YEARLY]: 'Annuel'
    };
    return periodicityNames[periodicity] || periodicity;
  }

  getPaymentStatusDisplayName(status: string): string {
    const statusNames: { [key: string]: string } = {
      'PENDING': 'En attente',
      'SUCCESS': 'Réussi', 
      'FAILED': 'Échoué'
    };
    return statusNames[status] || status;
  }

  formatAmount(amount: number, currency: Currency): string {
    return new Intl.NumberFormat('fr-FR', {
      style: 'currency',
      currency: currency
    }).format(amount);
  }

  formatDate(dateString: string): string {
    return new Date(dateString).toLocaleDateString('fr-FR');
  }

  getUserInitials(): string {
    if (!this.user) return 'U';
    return (this.user.firstName?.charAt(0) || '') + (this.user.lastName?.charAt(0) || '') || 'U';
  }

  getUserDisplayName(): string {
    if (!this.user) return 'Utilisateur';
    if (this.user.firstName && this.user.lastName) {
      return `${this.user.firstName} ${this.user.lastName}`;
    }
    return this.user.username;
  }

  getRoleBadgeClass(): string {
    if (!this.user?.role) return 'badge bg-secondary';
    return this.roleService.getRoleBadgeClass(this.user.role);
  }

  getRoleLabel(): string {
    if (!this.user?.role) return 'Aucun rôle';
    return this.roleService.getRoleLabel(this.user.role);
  }

  getRoleDescription(): string {
    if (!this.user?.role) return 'Description non disponible';
    const roleInfo = this.availableRoles.find(r => r.value === this.user!.role);
    return roleInfo?.description || this.roleService.getRoleDescription(this.user.role);
  }

  getRoleIcon(role: string | UserRole): string {
    return this.roleService.getRoleIcon(role);
  }

  // Obtenir le rôle (peut être string ou UserRole)
  getUserRole(): string | UserRole | undefined {
    return this.user?.role;
  }

  // Pour le template, retourner un tableau pour la boucle
  getUserRoles(): (string | UserRole)[] {
    const role = this.user?.role;
    if (!role) return [];
    return Array.isArray(role) ? role : [role];
  }

  // Afficher le rôle
  getUserRoleDisplay(): string {
    if (!this.user?.role) return 'Aucun rôle';
    return this.getRoleLabel();
  }
}