import { Component, OnInit } from '@angular/core';
import { NavController, LoadingController } from '@ionic/angular';
import { NgForm } from '@angular/forms';
import { AuthService } from 'src/app/services/auth.service';
import { AlertService } from 'src/app/services/alert.service';
import { TranslateService } from '@ngx-translate/core';
import { FirebaseAuthService } from 'src/app/services/firebase-auth.service';
import { Browser } from '@capacitor/browser';
import { firstValueFrom } from 'rxjs';


@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
  standalone: false
})
export class LoginPage implements OnInit {

  private loading: HTMLIonLoadingElement | null = null;

  constructor(
    private authService: AuthService,
    private firebaseAuthService: FirebaseAuthService,
    private navCtrl: NavController,
    private alertService: AlertService,
    private translateService: TranslateService,
    private loadingCtrl: LoadingController
  ) { }
  ngOnInit() {
  }
  // Dismiss Login Modal
  dismissLogin() {
    this.navCtrl.navigateRoot('/landing');
  }
  // On Register button tap, dismiss login modal and open register modal
  registerModal() {
    this.navCtrl.navigateForward('/register');
  }

  // On Forgot text tap, dismiss login modal and open forgot modal
  forgotModal() {
    this.navCtrl.navigateForward('/forgot');
  }

  async login(form: NgForm) {
    this.loading = await this.loadingCtrl.create();
    await this.loading.present();

    try {
      const idToken = await this.firebaseAuthService.signInWithEmail(
        form.value.email,
        form.value.password
      );

      this.authService.loginWithFirebase(idToken).subscribe(
        (data: any) => {},
        (error: any) => {
          if (this.loading) this.loading.dismiss();
          if (JSON.stringify(error['status']) == '401') {
            this.alertService.presentToast(this.translateService.instant('alerts.login_error'));
          } else {
            this.alertService.presentToast(this.translateService.instant('alerts.error') + error['message']);
          }
        },
        () => { this.navigateAfterLogin(); }
      );
    } catch (e: any) {
      if (this.loading) this.loading.dismiss();
      const msg = this.getFirebaseErrorMessage(e.code);
      this.alertService.presentToast(msg);
    }
  }

  private async navigateAfterLogin() {
    try {
      await firstValueFrom(this.authService.user());
    } catch { }
    if (this.loading) this.loading.dismiss();
    this.navCtrl.navigateRoot('/dashboard');
    this.alertService.presentToast(this.translateService.instant('alerts.login'));
  }

  private getFirebaseErrorMessage(code: string): string {
    switch (code) {
      case 'auth/wrong-password':
      case 'auth/user-not-found':
      case 'auth/invalid-credential':
        return this.translateService.instant('alerts.login_error');
      case 'auth/too-many-requests':
        return this.translateService.instant('alerts.too_many_requests');
      default:
        return this.translateService.instant('alerts.error') + code;
    }
  }

  async loginApple() {
    this.loading = await this.loadingCtrl.create();
    await this.loading.present();

    try {
      const idToken = await this.firebaseAuthService.signInWithApple();

      this.authService.loginWithFirebase(idToken).subscribe(
        (data: any) => {},
        (error: any) => {
          if (this.loading) this.loading.dismiss();
          this.alertService.presentToast(this.translateService.instant('alerts.error') + error);
          console.log(error);
        },
        () => { this.navigateAfterLogin(); }
      );
    } catch (e) {
      if (this.loading) this.loading.dismiss();
      this.alertService.presentToast(this.translateService.instant('alerts.error') + e);
    }
  }

  async loginGoogle() {
    this.loading = await this.loadingCtrl.create();
    await this.loading.present();

    try {
      const idToken = await this.firebaseAuthService.signInWithGoogle();

      this.authService.loginWithFirebase(idToken).subscribe(
        (data: any) => {},
        (error: any) => {
          if (this.loading) this.loading.dismiss();
          this.alertService.presentToast(this.translateService.instant('alerts.error') + error);
          console.log(error);
        },
        () => { this.navigateAfterLogin(); }
      );
    } catch (err) {
      if (this.loading) this.loading.dismiss();
      this.alertService.presentToast(this.translateService.instant('alerts.error') + err);
      console.log(err);
    }
  }

  async openTerms() {
    await Browser.open({ url: 'https://jobheroapp.com/terminos-y-condiciones' });
  }
}
