import {Component, ElementRef, inject, OnInit, signal, viewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import { Router } from '@angular/router';
import {NgIf} from '@angular/common';
import {LoginService} from './login.service';
import {AccountService} from '../../core/auth/account.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.html',
  imports: [
    ReactiveFormsModule,
    NgIf
  ],
  styleUrl: './login.scss'
})
export class Login implements OnInit {
  username = viewChild.required<ElementRef>('username');
  authenticationError = signal(false);


  loginForm = new FormGroup({
    username: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    password: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.minLength(4)] }),
    rememberMe: new FormControl(false, { nonNullable: true, validators: [Validators.required] }),
  });

  private readonly accountService = inject(AccountService);
  private readonly loginService = inject(LoginService);
  private readonly router = inject(Router);

  protected showPassword: boolean = false;


  ngOnInit(): void {
    // if already authenticated then navigate to home page
  /*  this.accountService.identity().subscribe(() => {
      if (this.accountService.isAuthenticated()) {
        this.router.navigate(['']);
      }
    });*/
  }


  /**
   * Bascule la visibilité du mot de passe
   */
  togglePasswordVisibility(): void {
    this.showPassword = !this.showPassword;
  }

  /**
   * Gère la soumission du formulaire
   */
  login(): void {
    this.loginService.login(this.loginForm.getRawValue()).subscribe({
      next: () => {
        this.authenticationError.set(false);
        if (!this.router.getCurrentNavigation()) {
          // There were no routing during login (eg from navigationToStoredUrl)
          this.router.navigate(['chantier/dashboard']);
        }
      },
      error: () => this.authenticationError.set(true),
    });
  }


}
