import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { AuthService } from '../../core/auth.service';

/**
 * Page de connexion. Consomme /api/auth/login via AuthService.
 */
@Component({
  selector: 'app-login',
  standalone: true,
  imports: [FormsModule, RouterLink],
  template: `
    <div class="carte-auth">
      <h1>Connexion</h1>
      <form (ngSubmit)="soumettre()">
        <div class="champ">
          <label for="email">Adresse e-mail</label>
          <input
            id="email"
            name="email"
            type="email"
            [(ngModel)]="email"
            required
            autocomplete="email"
          />
        </div>
        <div class="champ">
          <label for="password">Mot de passe</label>
          <input
            id="password"
            name="password"
            type="password"
            [(ngModel)]="password"
            required
            autocomplete="current-password"
          />
        </div>

        @if (erreur()) {
          <p class="message-erreur">{{ erreur() }}</p>
        }

        <button
          class="btn btn-primaire bloc"
          type="submit"
          [disabled]="chargement()"
        >
          {{ chargement() ? 'Connexion…' : 'Se connecter' }}
        </button>
      </form>
      <p class="lien-secondaire">
        Pas de compte ? <a routerLink="/register">Créer un compte</a>
      </p>
    </div>
  `,
  styleUrl: './auth.scss',
})
export class LoginComponent {
  private readonly auth = inject(AuthService);
  private readonly router = inject(Router);
  private readonly route = inject(ActivatedRoute);

  email = '';
  password = '';
  readonly chargement = signal(false);
  readonly erreur = signal<string | null>(null);

  soumettre(): void {
    if (!this.email || !this.password) {
      return;
    }
    this.chargement.set(true);
    this.erreur.set(null);
    this.auth.login(this.email, this.password).subscribe({
      next: () => {
        const redirige =
          this.route.snapshot.queryParamMap.get('redirige') ?? '/dashboard';
        this.router.navigateByUrl(redirige);
      },
      error: (e: HttpErrorResponse) => {
        this.chargement.set(false);
        this.erreur.set(
          e.error?.error ?? 'Connexion impossible. Vérifiez vos identifiants.',
        );
      },
    });
  }
}
