import { Injectable, NgZone } from '@angular/core';
import { Capacitor } from '@capacitor/core';
import { NavController } from '@ionic/angular';
import { EnvService } from './env.service';
import { AlertService } from './alert.service';
import { EventService } from './event.service';

declare var OneSignalPlugin: any;

@Injectable({
  providedIn: 'root'
})
export class OneSignalService {
  private initialized = false;

  constructor(
    private env: EnvService,
    private navCtrl: NavController,
    private alertService: AlertService,
    private events: EventService,
    private ngZone: NgZone,
  ) { }

  async init(): Promise<void> {
    if (this.initialized || !Capacitor.isNativePlatform()) return;

    try {
      OneSignalPlugin.initialize(this.env.ONESIGNAL_APP_ID);

      OneSignalPlugin.Notifications.requestPermission(true).then((accepted: boolean) => {
        console.log('OneSignal permission:', accepted ? 'accepted' : 'denied');
      });

      // Foreground: show alert + navigate
      OneSignalPlugin.Notifications.addEventListener('foregroundWillDisplay', (event: any) => {
        const notification = event.getNotification();
        notification.display();
        this.ngZone.run(() => {
          this.alertService.presentAlert(notification.title, notification.body, ['OK']);
          this.navigateByTitle(notification.title);
        });
      });

      // Tap on notification: navigate only
      OneSignalPlugin.Notifications.addEventListener('click', (event: any) => {
        const title = event.notification?.title;
        this.ngZone.run(() => this.navigateByTitle(title));
      });

      this.initialized = true;
    } catch (error) {
      console.error('Error initializing OneSignal:', error);
    }
  }

  private navigateByTitle(title: string): void {
    if (title === 'Proveedor: hay nueva postulación' || title === 'Hero: there is a new postulation') {
      this.navCtrl.navigateRoot('/postulations');
      this.events.publish('refreshpostulations', 'data');
    } else if (title === 'Búsqueda Finalizada' || title === 'Search finished') {
      this.navCtrl.navigateRoot('/contracts');
    } else if (title === 'Usuario: el proveedor ha iniciado el servicio' || title === 'User: the Hero has started the service') {
      this.navCtrl.navigateRoot('/contracts');
    }
  }

  async setUserId(userId: number | string): Promise<void> {
    if (!Capacitor.isNativePlatform()) return;
    try {
      OneSignalPlugin.login(String(userId));
      OneSignalPlugin.User.addTag('iChamba_ID', String(userId));
    } catch (error) {
      console.error('Error setting OneSignal user:', error);
    }
  }

  async setUserRole(roleId: number | string): Promise<void> {
    if (!Capacitor.isNativePlatform()) return;
    try {
      OneSignalPlugin.User.addTag('iChamba_Role', String(roleId));
    } catch (error) {
      console.error('Error setting OneSignal role tag:', error);
    }
  }

  async clearTags(): Promise<void> {
    if (!Capacitor.isNativePlatform()) return;
    try {
      OneSignalPlugin.User.removeTags(['iChamba_ID', 'iChamba_Role']);
    } catch (error) {
      console.error('Error clearing OneSignal tags:', error);
    }
  }

  async logout(): Promise<void> {
    await this.clearTags();
    if (Capacitor.isNativePlatform()) {
      try {
        OneSignalPlugin.logout();
      } catch (error) {
        console.error('Error logging out OneSignal:', error);
      }
    }
  }

  async getPlayerId(): Promise<string | null> {
    if (!Capacitor.isNativePlatform()) return null;
    try {
      const id = await OneSignalPlugin.User.pushSubscription.getId();
      return id || null;
    } catch (error) {
      console.error('Error getting OneSignal player ID:', error);
      return null;
    }
  }
}
