import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { Platform, NavController, LoadingController } from '@ionic/angular';
import { EventService } from './services/event.service';
import { StatusBar, Style } from '@capacitor/status-bar';
import { SplashScreen } from '@capacitor/splash-screen';
import { Browser } from '@capacitor/browser';
import { AuthService } from './services/auth.service';
import { LanguageService } from './services/language.service';
import { AlertService } from './services/alert.service';
import { TranslateService } from '@ngx-translate/core';
import { Capacitor } from '@capacitor/core';
import { OneSignalService } from './services/onesignal.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  standalone: false
})
export class AppComponent implements OnInit {

  private loading: any;
  userRole: number = 0;

  constructor(
    private platform: Platform,
    public authService: AuthService,
    private languageService: LanguageService,
    private translateService: TranslateService,
    private navCtrl: NavController,
    private events: EventService,
    private alertService: AlertService,
    private loadingCtrl: LoadingController,
    private oneSignalService: OneSignalService,
    private cdr: ChangeDetectorRef,
  ) {
    this.initializeApp();
    this.events.subscribe('set_role', role => {
      this.userRole = role ?? 0;
      this.cdr.detectChanges();
      this.setupOneSignalUser(role);
    });
  }

  ngOnInit() {
    this.userRole = this.authService.userRole;
  }

  async initializeApp() {
    await this.platform.ready();

    // Solo ejecutar plugins nativos en dispositivos móviles
    if (Capacitor.isNativePlatform()) {
      await StatusBar.setStyle({ style: Style.Light });
      await StatusBar.setOverlaysWebView({ overlay: false });
      await StatusBar.setBackgroundColor({ color: '#0080ff' });

      // Initialize OneSignal push notifications
      await this.oneSignalService.init();
    }

    this.languageService.getDefaultLanguage();
  }

  private async setupOneSignalUser(role: number) {
    if (this.authService.token && this.authService.token.user_id) {
      await this.oneSignalService.setUserId(this.authService.token.user_id);
      await this.oneSignalService.setUserRole(role);
    }
  }

  // When Logout Button is pressed
  async logout() {
    this.loading = await this.loadingCtrl.create();
    await this.loading.present();

    this.authService.logout().subscribe(
      async data => {
        this.alertService.presentToast(this.translateService.instant('alerts.logout'));
        // Clear OneSignal user tags on logout
        await this.oneSignalService.logout();
      },
      error => {
        this.loading.dismiss();
        console.log(error);
      },
      () => {
        this.loading.dismiss();
        this.navCtrl.navigateRoot('/landing');
      }
    );
  }

  async openUrl(url: string) {
    await Browser.open({ url });
  }
}
