import { Component, OnInit } from '@angular/core';
import { NavController, LoadingController } from '@ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
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';
import { Browser } from '@capacitor/browser';

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

  loading: HTMLIonLoadingElement | null = null;
  terms = false;

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

  ngOnInit() { }

  dismissRegister() {
    this.navCtrl.navigateRoot('/landing');
  }

  loginModal() {
    this.navCtrl.navigateForward('/login');
  }

  updateChecked() {
    this.terms = !this.terms;
  }

  async register(form: NgForm) {
    if (!this.terms) {
      this.alertService.presentToast(this.translateService.instant('alerts.signup_error_3'));
      return;
    }

    const { name, email, phone, password, password1 } = form.value;

    if (!name || !email || !phone || !password || !password1) {
      this.alertService.presentToast(this.translateService.instant('alerts.signup_error_2'));
      return;
    }

    if (password !== password1) {
      this.alertService.presentToast(this.translateService.instant('alerts.signup_error_1'));
      return;
    }

    this.loading = await this.loadingCtrl.create();
    await this.loading.present();

    try {
      // Firebase crea la cuenta con email + password
      const idToken = await this.firebaseAuthService.registerWithEmail(email, password);

      // Backend crea el perfil y devuelve el token de la app
      this.authService.registerWithFirebase(idToken, name, phone, email).subscribe(
        (data: any) => {},
        (error: any) => {
          if (this.loading) this.loading.dismiss();
          if (error['status'] === 422) {
            this.alertService.presentToast(this.translateService.instant('alerts.signup_error'));
          } else {
            this.alertService.presentToast(this.translateService.instant('alerts.error') + error['message']);
          }
        },
        () => {
          if (this.loading) this.loading.dismiss();
          this.alertService.presentToast(this.translateService.instant('alerts.signup'));
          this.navCtrl.navigateRoot('/dashboard');
        }
      );
    } catch (e: any) {
      if (this.loading) this.loading.dismiss();
      if (e.code === 'auth/email-already-in-use') {
        this.alertService.presentToast(this.translateService.instant('alerts.signup_error'));
      } else {
        this.alertService.presentToast(this.translateService.instant('alerts.error') + e.message);
      }
    }
  }

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