import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { tap, catchError, finalize } from 'rxjs/operators';

// Core services
import { EstairService } from '../../../core/services/estair.service';
import { ChapsService } from '../../../core/services/chaps.service';

// Environment
import { environment } from '../../../../environments/environment';

/**
 * Service spécialisé pour la gestion du support client
 */
@Injectable()
export class SupportService {

  // État du service
  private loadingSubject = new BehaviorSubject<boolean>(false);
  private ticketsSubject = new BehaviorSubject<any[]>([]);
  private usersSubject = new BehaviorSubject<any[]>([]);

  // Observables publics
  public loading$ = this.loadingSubject.asObservable();
  public tickets$ = this.ticketsSubject.asObservable();
  public users$ = this.usersSubject.asObservable();

  // Cache local
  private ticketsCache: any[] = [];
  private usersCache: any[] = [];
  private lastUpdate: number = 0;
  private readonly CACHE_DURATION = 5 * 60 * 1000; // 5 minutes

  constructor(
    private estairService: EstairService,
    private chapsService: ChapsService
  ) {}

  /**
   * Récupère les tickets
   */
  getTickets(): Observable<any[]> {
    if (this.isCacheValid() && this.ticketsCache.length > 0) {
      return this.tickets$;
    }
    return this.loadTickets();
  }

  /**
   * Récupère les utilisateurs
   */
  getUsers(): Observable<any[]> {
    if (this.isCacheValid() && this.usersCache.length > 0) {
      return this.users$;
    }
    return this.loadUsers();
  }

  /**
   * Charge les tickets
   */
  loadTickets(): Observable<any[]> {
    this.loadingSubject.next(true);

    // En mode développement, utiliser des données de test
    if (!environment.production) {
      return new Observable<any[]>(observer => {
        setTimeout(() => {
          const testData = this.generateTicketsTestData();
          this.ticketsCache = testData;
          this.lastUpdate = Date.now();
          this.ticketsSubject.next(testData);
          observer.next(testData);
          observer.complete();
          this.loadingSubject.next(false);
        }, 700);
      });
    }

    return this.estairService.getAll('helpdesk').pipe(
      tap(data => {
        this.ticketsCache = data;
        this.lastUpdate = Date.now();
        this.ticketsSubject.next(data);
      }),
      catchError(error => {
        console.error('Erreur lors du chargement des tickets:', error);
        const testData = this.generateTicketsTestData();
        this.ticketsCache = testData;
        this.ticketsSubject.next(testData);
        return new Observable<any[]>(observer => {
          observer.next(testData);
          observer.complete();
        });
      }),
      finalize(() => this.loadingSubject.next(false))
    );
  }

  /**
   * Charge les utilisateurs
   */
  loadUsers(): Observable<any[]> {
    this.loadingSubject.next(true);

    // En mode développement, utiliser des données de test
    if (!environment.production) {
      return new Observable<any[]>(observer => {
        setTimeout(() => {
          const testData = this.generateUsersTestData();
          this.usersCache = testData;
          this.lastUpdate = Date.now();
          this.usersSubject.next(testData);
          observer.next(testData);
          observer.complete();
          this.loadingSubject.next(false);
        }, 500);
      });
    }

    return this.estairService.getAll('users').pipe(
      tap(data => {
        this.usersCache = data;
        this.lastUpdate = Date.now();
        this.usersSubject.next(data);
      }),
      catchError(error => {
        console.error('Erreur lors du chargement des utilisateurs:', error);
        const testData = this.generateUsersTestData();
        this.usersCache = testData;
        this.usersSubject.next(testData);
        return new Observable<any[]>(observer => {
          observer.next(testData);
          observer.complete();
        });
      }),
      finalize(() => this.loadingSubject.next(false))
    );
  }

  /**
   * Génère des données de test pour les tickets
   */
  private generateTicketsTestData(): any[] {
    return [
      {
        id: 1,
        uuid: 'tick-001',
        ticket_number: '#001',
        subject: 'Problème émission billet',
        description: 'Impossible d\'émettre un billet pour le vol AF718',
        priority: 'high',
        status: 'open',
        account_name: 'Agence Voyage Plus',
        requester: 'Jean Dupont',
        assigned_to: 'Support Technique',
        created_at: new Date('2024-01-20'),
        updated_at: new Date('2024-01-20')
      },
      {
        id: 2,
        uuid: 'tick-002',
        ticket_number: '#002',
        subject: 'Question tarification',
        description: 'Demande d\'information sur les nouvelles grilles tarifaires',
        priority: 'medium',
        status: 'resolved',
        account_name: 'Travel Express SARL',
        requester: 'Marie Martin',
        assigned_to: 'Support Commercial',
        created_at: new Date('2024-01-18'),
        updated_at: new Date('2024-01-19')
      },
      {
        id: 3,
        uuid: 'tick-003',
        ticket_number: '#003',
        subject: 'Demande formation utilisateur',
        description: 'Formation sur les nouvelles fonctionnalités du système',
        priority: 'low',
        status: 'closed',
        account_name: 'Mondial Tours',
        requester: 'Ahmed Diallo',
        assigned_to: 'Support Formation',
        created_at: new Date('2024-01-15'),
        updated_at: new Date('2024-01-17')
      },
      {
        id: 4,
        uuid: 'tick-004',
        ticket_number: '#004',
        subject: 'Erreur calcul commission',
        description: 'Anomalie dans le calcul des commissions sur les billets',
        priority: 'high',
        status: 'in_progress',
        account_name: 'Safari Adventures',
        requester: 'Fatou Sow',
        assigned_to: 'Support Technique',
        created_at: new Date('2024-01-22'),
        updated_at: new Date('2024-01-23')
      }
    ];
  }

  /**
   * Génère des données de test pour les utilisateurs
   */
  private generateUsersTestData(): any[] {
    return [
      {
        id: 1,
        uuid: 'user-001',
        name: 'Admin Système',
        email: 'admin@ceteris.com',
        role: 'administrator',
        status: 'active',
        last_login: new Date('2024-01-24'),
        created_at: new Date('2024-01-01')
      },
      {
        id: 2,
        uuid: 'user-002',
        name: 'Support Technique',
        email: 'support.tech@ceteris.com',
        role: 'support_tech',
        status: 'active',
        last_login: new Date('2024-01-23'),
        created_at: new Date('2024-01-05')
      },
      {
        id: 3,
        uuid: 'user-003',
        name: 'Support Commercial',
        email: 'support.com@ceteris.com',
        role: 'support_commercial',
        status: 'active',
        last_login: new Date('2024-01-22'),
        created_at: new Date('2024-01-10')
      },
      {
        id: 4,
        uuid: 'user-004',
        name: 'Gestionnaire Comptes',
        email: 'comptes@ceteris.com',
        role: 'account_manager',
        status: 'inactive',
        last_login: new Date('2024-01-15'),
        created_at: new Date('2024-01-12')
      }
    ];
  }

  /**
   * Rafraîchit les données
   */
  refreshData(): void {
    this.invalidateCache();
    this.loadTickets().subscribe();
    this.loadUsers().subscribe();
  }

  /**
   * Vérifie si le cache est valide
   */
  private isCacheValid(): boolean {
    const age = Date.now() - this.lastUpdate;
    return age < this.CACHE_DURATION;
  }

  /**
   * Invalide le cache
   */
  private invalidateCache(): void {
    this.lastUpdate = 0;
    this.ticketsCache = [];
    this.usersCache = [];
  }

  /**
   * Nettoie le service
   */
  cleanup(): void {
    this.loadingSubject.complete();
    this.ticketsSubject.complete();
    this.usersSubject.complete();
  }
}


