import { Injectable } from '@angular/core';
import { Capacitor } from '@capacitor/core';
import { EnvService } from './env.service';
import { Router } from '@angular/router';

declare var OneSignalPlugin: any;

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

  constructor(
    private env: EnvService,
    private router: Router
  ) { }

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

    try {
      // Initialize OneSignal
      OneSignalPlugin.initialize(this.env.ONESIGNAL_APP_ID);

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

      // Handle notification clicks
      OneSignalPlugin.Notifications.addEventListener('click', (event: any) => {
        console.log('OneSignal notification clicked:', event);
        this.handleNotificationClick(event);
      });

      // Handle foreground notifications
      OneSignalPlugin.Notifications.addEventListener('foregroundWillDisplay', (event: any) => {
        console.log('OneSignal notification received in foreground:', event);
        // Display the notification
        event.getNotification().display();
      });

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

  async setUserId(userId: number | string): Promise<void> {
    if (!Capacitor.isNativePlatform()) {
      return;
    }

    try {
      // Set user tag for targeting
      OneSignalPlugin.User.addTag('iChamba_ID', String(userId));
      console.log('OneSignal user tag set:', userId);
    } catch (error) {
      console.error('Error setting OneSignal user tag:', error);
    }
  }

  async setUserRole(roleId: number | string): Promise<void> {
    if (!Capacitor.isNativePlatform()) {
      return;
    }

    try {
      OneSignalPlugin.User.addTag('iChamba_Role', String(roleId));
      console.log('OneSignal role tag set:', 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']);
      console.log('OneSignal tags cleared');
    } catch (error) {
      console.error('Error clearing OneSignal tags:', error);
    }
  }

  async logout(): Promise<void> {
    await this.clearTags();
  }

  private handleNotificationClick(event: any): void {
    const data = event?.notification?.additionalData;

    if (data) {
      // Handle navigation based on notification data
      if (data.route) {
        this.router.navigate([data.route]);
      } else if (data.type) {
        switch (data.type) {
          case 'contract':
            this.router.navigate(['/contracts']);
            break;
          case 'postulation':
            this.router.navigate(['/postulations']);
            break;
          default:
            this.router.navigate(['/dashboard']);
        }
      }
    }
  }

  async getPlayerId(): Promise<string | null> {
    if (!Capacitor.isNativePlatform()) {
      return null;
    }

    try {
      const deviceState = await OneSignalPlugin.User.pushSubscription.getId();
      return deviceState || null;
    } catch (error) {
      console.error('Error getting OneSignal player ID:', error);
      return null;
    }
  }
}
