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-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  standalone: false
})
export class LoginComponent implements OnInit {
  @Output() loginSuccess = new EventEmitter<void>();
  
  loginForm: FormGroup;
  
  constructor(
    private formBuilder: FormBuilder,
    private authService: AuthService,
    private loadingController: LoadingController,
    private toastController: ToastController
  ) { 
    this.loginForm = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]]
    });
  }

  ngOnInit() {}
  
  // Variable para controlar si hay un proceso de login en curso
  private isLoggingIn = false;

  async onSubmit() {
    // Evitar múltiples clicks
    if (this.isLoggingIn) {
      console.log('Ya hay un proceso de login en curso, ignorando click');
      return;
    }
    
    if (this.loginForm.invalid) {
      this.markFormGroupTouched(this.loginForm);
      return;
    }
    
    // Marcar que hay un proceso en curso
    this.isLoggingIn = true;
    console.log('Iniciando proceso de login');
    
    const loading = await this.loadingController.create({
      message: 'Iniciando sesión...',
      spinner: 'circles'
    });
    await loading.present();
    
    // Intentar login con el backend real
    this.authService.login(this.loginForm.value).subscribe({
      next: () => {
        loading.dismiss();
        this.isLoggingIn = false; // Resetear flag
        this.loginSuccess.emit();
      },
      error: (error) => {
        console.error('Error en login:', error);
        loading.dismiss();
        this.isLoggingIn = false; // Resetear flag
        
        // Si el backend rechaza, intentar con el usuario demo
        if (this.loginForm.value.email === 'usuario@ejemplo.com' && 
            this.loginForm.value.password === 'password123') {
          
          // Simular login exitoso para el usuario demo
          this.isLoggingIn = true; // Volver a establecer el flag
          this.authService.simulateAuth({
            id: '1',
            name: 'Usuario Demo',
            email: 'usuario@ejemplo.com',
            profilePic: '',
            preferences: {
              notifications: true,
              favoriteClasses: []
            }
          }).subscribe({
            next: () => {
              this.isLoggingIn = false;
              this.loginSuccess.emit();
            },
            error: () => {
              this.isLoggingIn = false;
              this.showToast('Error al iniciar sesión');
            }
          });
        } else {
          this.showToast('Credenciales incorrectas');
        }
      }
    });
  }
  
  private markFormGroupTouched(formGroup: FormGroup) {
    Object.values(formGroup.controls).forEach(control => {
      control.markAsTouched();
      if (control instanceof FormGroup) {
        this.markFormGroupTouched(control);
      }
    });
  }
  
  async showToast(message: string) {
    const toast = await this.toastController.create({
      message,
      duration: 2000,
      position: 'bottom',
      color: 'danger'
    });
    await toast.present();
  }
}