import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { LoadingController, ToastController } from '@ionic/angular';
import { AuthService } from '../../../../services/auth.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss'],
  standalone:false
})
export class RegisterComponent implements OnInit {
  @Output() registerSuccess = new EventEmitter<void>();
  
  registerForm: FormGroup;
  
  constructor(
    private formBuilder: FormBuilder,
    private authService: AuthService,
    private loadingController: LoadingController,
    private toastController: ToastController
  ) { 
    this.registerForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]],
      confirmPassword: ['', [Validators.required]]
    }, { validators: this.passwordMatchValidator });
  }

  ngOnInit() {}
  
  passwordMatchValidator(form: FormGroup) {
    const password = form.get('password')?.value;
    const confirmPassword = form.get('confirmPassword')?.value;
    
    if (password === confirmPassword) {
      form.get('confirmPassword')?.setErrors(null);
      return null;
    } else {
      form.get('confirmPassword')?.setErrors({ mismatch: true });
      return { mismatch: true };
    }
  }
  
  // Variable para controlar si hay un proceso de registro en curso
  private isRegistering = false;

  async onSubmit() {
    // Evitar múltiples clicks
    if (this.isRegistering) {
      console.log('Ya hay un proceso de registro en curso, ignorando click');
      return;
    }
    
    if (this.registerForm.invalid) {
      this.markFormGroupTouched(this.registerForm);
      return;
    }
    
    // Marcar que hay un proceso en curso
    this.isRegistering = true;
    console.log('Iniciando proceso de registro');
    
    const loading = await this.loadingController.create({
      message: 'Creando cuenta...',
      spinner: 'circles'
    });
    await loading.present();
    
    // Registrar el usuario en el servidor
    this.authService.register({
      name: this.registerForm.value.name,
      email: this.registerForm.value.email,
      password: this.registerForm.value.password
    }).subscribe({
      next: () => {
        loading.dismiss();
        this.isRegistering = false; // Resetear flag
        this.registerSuccess.emit();
        this.showToast('Cuenta creada correctamente', 'success');
      },
      error: (error) => {
        console.error('Error en registro:', error);
        loading.dismiss();
        this.isRegistering = false; // Resetear flag
        
        if (error?.error?.message === 'El usuario ya existe') {
          this.showToast('Este email ya está registrado');
        } else {
          this.showToast('Error al crear la cuenta');
        }
      }
    });
  }
  
  private markFormGroupTouched(formGroup: FormGroup) {
    Object.values(formGroup.controls).forEach(control => {
      control.markAsTouched();
      if (control instanceof FormGroup) {
        this.markFormGroupTouched(control);
      }
    });
  }
  
  async showToast(message: string, color: string = 'danger') {
    const toast = await this.toastController.create({
      message,
      duration: 2000,
      position: 'bottom',
      color: color
    });
    await toast.present();
  }
}