import { Component, signal } from '@angular/core'; // Import OnInit
import { Validators, FormBuilder, FormGroup } from '@angular/forms'; // Import FormGroup
import { Router } from '@angular/router';
import { toast } from 'ngx-sonner';
import { Auth } from 'src/app/core/services/auth';

@Component({
  selector: 'app-login',
  templateUrl: './login.html',
  styleUrl: './login.css',
  standalone: false,
})
export class Login {
  showPassword = false;
  loading = signal(false);
  errorMsg = signal('');
  form!: FormGroup;

  constructor(private fb: FormBuilder, private auth: Auth, private router: Router) {
    this.form = this.fb.group({
      identifiant: ['', [Validators.required]],
      password: ['', [Validators.required, Validators.minLength(8)]],
    });
  }

  async submit() {
    this.errorMsg.set('');
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    this.loading.set(true);
    try {
      const { identifiant, password } = this.form.value;
      //await this.auth.login(identifiant!, password!);
      await this.router.navigateByUrl('/');
      toast.success('Connexion réussie ! Bienvenue.');
    } catch (e: any) {
      this.errorMsg.set(
        e?.message || e?.error?.message || 'Échec de connexion. Veuillez réessayer.'
      );
      toast.error(this.errorMsg(), { duration: 5000 });
    } finally {
      this.loading.set(false);
    }
  }
}
