import { Component, NgZone } from '@angular/core';
import { App, URLOpenListenerEvent } from '@capacitor/app';
import { Capacitor } from '@capacitor/core';
import { SplashScreen } from '@capacitor/splash-screen';
import { api } from '@enums/api.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { environment } from '@environments/environment';
import { IonicModule, NavController, Platform } from '@ionic/angular';
import { PushService } from '@services//push.service';
import { FirebaseService } from '@services/firebase.service';
import { HttpRequestService } from '@services/http-request.service';
import { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';
import { ShareExtension } from 'capacitor-share-extension';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  standalone: true,
  imports: [IonicModule]
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private zone: NgZone,
    private navCtrl: NavController,
    private pushService: PushService,
    private readonly firebaseService: FirebaseService,
    private stateManagementService: StateManagementService,
    private utilityService: UtilityService,
    private httpRequestService: HttpRequestService,
  ) {
    this.insertScript();
    this.initializeApp();
    this.getCommonData();
  }

  insertScript() {
    const url = `https://maps.googleapis.com/maps/api/js?key=${environment.mapKey}&libraries=places&callback=cb`;
    const x: any = document.createElement('SCRIPT');
    x.src = url;
    document.body.appendChild(x);
  }

  initializeApp() {
    this.firebaseService.initialize();
    this.platform.ready().then(() => {
      this.stateManagementService.fetchNotificationCounts();
      this.utilityService.handleInternetStatus();
      App.addListener('resume', () => {
        this.stateManagementService.fetchNotificationCounts();
      });
      setTimeout(() => {
        SplashScreen.hide();
      }, 4000);
      this.handleDeepLinking();
      this.handleMentionsClick();
      if (Capacitor.isPluginAvailable('PushNotifications')) {
        this.pushService.init();
      }
      if (Capacitor.isPluginAvailable('ShareExtension')) {
        window.addEventListener('sendIntentReceived', () => {
          this.checkIntent();
        });
        this.checkIntent();
      }
    });
  }

  handleMentionsClick() {
    document.addEventListener('click', async (e: any) => {
      e.stopPropagation();
      this.zone.run(() => {
        if (e.target.classList.contains('mention-user') && +e.target.getAttribute('data-id')) {
          this.navCtrl.navigateForward(
            Roots.page + '/' + Roots.shravakOtherProfile.replace(':id', e.target.getAttribute('data-id'))
          );
        } else if (e.target.classList.contains('mention-sant') && +e.target.getAttribute('data-id')) {
          this.navCtrl.navigateForward(
            Roots.page + '/' + Roots.santViewProfile.replace(':santId', e.target.getAttribute('data-id'))
          );
        } else if (e.target.classList.contains('mention-sangh') && +e.target.getAttribute('data-id')) {
          this.navCtrl.navigateForward(
            Roots.page + '/' + Roots.sanghProfile.replace(':sanghId', e.target.getAttribute('data-id'))
          );
        }
      }, false);
    });
  }

  async handleDeepLinking() {
    App.addListener('appUrlOpen', (event: URLOpenListenerEvent) => {
      this.zone.run(async () => {
        const { hostname } = new URL(event.url);
        const pathArray = event.url.split(hostname);
        const appPath = pathArray.pop();
        if (appPath) {
          if (appPath.includes('user/invitation')) {
            this.navCtrl.navigateForward(Roots.page + '/' + Roots.shravakFeeds);
          } else {
            this.navCtrl.navigateForward(appPath);
          }
        }
      });
    });
  }

  async checkIntent() {
    try {
      const result: any = await ShareExtension.checkSendIntentReceived();
      if (result?.payload?.length) {
        this.stateManagementService.shareData = result.payload;
        this.zone.run(() => {
          setTimeout(async () => {
            const userData = await this.stateManagementService.storage.get(GJainStorage.userData);
            const navOption = {
              state: {
                isUpdate: false,
                fromFeed: true,
                redirectTo: 'page/shravak-feeds',
                type: 1,
                type_id: userData.id,
                userAvatar: userData?.avatar,
                userName: userData?.name,
                send: 1
              },
            };
            this.navCtrl.navigateForward(Roots.page + '/' + Roots.postFeed, navOption);
          }, 500);
        });
      } else {
        this.stateManagementService.shareData = null;
      }
    } catch (error) {
      console.log({ error });
    }
  }

  getCommonData(): void {
    this.httpRequestService.get(api.commonDropdown).then((res: any) => {
      this.stateManagementService.common = res;
    });
  }

}
