import { NgClass, NgIf } from '@angular/common';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { IonicModule, NavController } from '@ionic/angular';

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 { VerifyLoginResponse } from '@interfaces/common';
import { AlertService } from '@services/alert.service';
import { FirebaseService } from '@services/firebase.service';
import { HttpRequestService } from '@services/http-request.service';
import { PushService } from '@services/push.service';
import { StateManagementService } from '@services/state-management.service';

@Component({
  selector: 'app-otp',
  templateUrl: './otp.page.html',
  styleUrls: ['./otp.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, NgClass]
})
export class OtpPage implements OnInit, OnDestroy {
  otpUserValue: number;
  resendFlag = false;
  paramsData: any;
  resendEnable = true;
  timer: string;
  interval: any;
  otpVerified = false;

  constructor(
    private httpRequestService: HttpRequestService,
    private stateManagementService: StateManagementService,
    private alert: AlertService,
    private navCtrl: NavController,
    private pushService: PushService,
    private router: Router,
    private firebaseService: FirebaseService
  ) { }

  ngOnInit() {
    this.paramsData = this.router.getCurrentNavigation().extras?.state;
    this.initTimer();
    this.firebaseService.otpVerified$.subscribe(() => {
      this.otpVerified = true;
      this.afterOtpVerified();
    });
  }

  initTimer() {
    let seconds = 60;
    this.interval = setInterval(() => {
      if (seconds > 0) {
        seconds--;
        this.timer = `00:${(seconds > 10 ? seconds : '0' + seconds)}`;
      } else {
        this.timer = null;
        this.resendEnable = false;
        clearInterval(this.interval);
      }
    }, 1000);
  }

  async afterOtpVerified() {
    if (!this.otpVerified) { return; }
    let loginPayLoad: any = {
      email: this.paramsData.phoneNumber,
      country_code: this.paramsData.countryCode,
      via: 'OTP',
      verified: 1,
    };
    let apiUrl = '';
    if (this.paramsData.redirectionFrom === 'login') {
      apiUrl = api.login;
      loginPayLoad = {
        ...loginPayLoad,
        app_version: 1
      }
    } else {
      loginPayLoad = {
        ...loginPayLoad,
        name: this.paramsData.signupData.name,
        dharma: this.paramsData.signupData.dharma,
        birth_date: this.paramsData.signupData.birth_date
      };
      apiUrl = api.signUp;
    }
    const response: VerifyLoginResponse = await this.httpRequestService.post(apiUrl, loginPayLoad);
    if (response.status === 200) {
      this.stateManagementService.storage.set(GJainStorage.loginType, 2);
      this.stateManagementService.token = response.token;
      this.stateManagementService.storage.set(GJainStorage.userData, response.user);
      if (this.paramsData.redirectionFrom === 'login') {
        this.stateManagementService.fetchNotificationCounts();
        this.navCtrl.navigateRoot(Roots.page + '/' + Roots.shravakFeeds);
      } else {
        this.navCtrl.navigateRoot(Roots.page + '/' + Roots.createdAccount);
      }
      this.otpVerified = false;
      this.pushService.registerPushToken();
    }
    this.alert.showToaster(response.message);
  }

  async verifyOtp() {
    const otpVal = String(this.otpUserValue);
    this.alert.showLoader();
    try {
      const auth = environment.production ? (await this.firebaseService.confirmVerificationCode(otpVal)).user : 1;
      if (auth) {
        this.otpVerified = true;
        this.afterOtpVerified();
      }
    } catch (error) {
      if (!error.error && error.message !== 'signIn failed.') { this.alert.showToasterError(error.message); }
    } finally {
      this.alert.hideLoader();
    }
  }

  resendOtp() {
    this.resendFlag = true;
    this.firebaseService.signInWithPhoneNumber({ phoneNumber: this.paramsData.countryCode + this.paramsData.phoneNumber })
      .then(() => {
        this.resendFlag = false;
        this.initTimer();
        this.alert.showToaster('OTP resent successfully!');
      }).catch((error) => {
        this.alert.showToasterError(error.message);
        this.alert.hideLoader();
      });
  }

  backToLogin() {
    this.navCtrl.navigateRoot(Roots.auth + '/' + Roots.login);
  }

  ngOnDestroy() {
    this.otpVerified = false;
  }

}
