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

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

  private loading: HTMLIonLoadingElement | null = null;

  constructor(
    private firebaseAuthService: FirebaseAuthService,
    private navCtrl: NavController,
    private alertService: AlertService,
    private translateService: TranslateService,
    private loadingCtrl: LoadingController
  ) { }

  ngOnInit() { }

  dismissForgot() {
    this.navCtrl.back();
  }

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

    try {
      await this.firebaseAuthService.sendPasswordReset(form.value.email);
      if (this.loading) this.loading.dismiss();
      this.alertService.presentToast(this.translateService.instant('alerts.reset_pass'));
      this.dismissForgot();
    } catch (e: any) {
      if (this.loading) this.loading.dismiss();
      if (e.code === 'auth/user-not-found') {
        // Por seguridad mostramos el mismo mensaje aunque no exista el usuario
        this.alertService.presentToast(this.translateService.instant('alerts.reset_pass'));
        this.dismissForgot();
      } else {
        this.alertService.presentToast(this.translateService.instant('alerts.error') + e.message);
      }
    }
  }
}
