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

/**
 * Page d'inscription. Consomme /api/auth/register via AuthService.
 */
@Component({
  selector: 'app-register',
  standalone: true,
  imports: [FormsModule, RouterLink],
  template: `
    <div class="carte-auth">
      <h1>Créer un compte</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
            minlength="8"
            autocomplete="new-password"
          />
        </div>
        <div class="champ">
          <label for="confirmation">Confirmer le mot de passe</label>
          <input
            id="confirmation"
            name="confirmation"
            type="password"
            [(ngModel)]="confirmation"
            required
            autocomplete="new-password"
          />
        </div>

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

        <button
          class="btn btn-primaire bloc"
          type="submit"
          [disabled]="chargement()"
        >
          {{ chargement() ? 'Création…' : "S'inscrire" }}
        </button>
      </form>
      <p class="lien-secondaire">
        Déjà inscrit ? <a routerLink="/login">Se connecter</a>
      </p>
    </div>
  `,
  styleUrl: './auth.scss',
})
export class RegisterComponent {
  private readonly auth = inject(AuthService);
  private readonly router = inject(Router);

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

  soumettre(): void {
    if (!this.email || !this.password) {
      return;
    }
    if (this.password.length < 8) {
      this.erreur.set('Le mot de passe doit contenir au moins 8 caractères.');
      return;
    }
    if (this.password !== this.confirmation) {
      this.erreur.set('Les mots de passe ne correspondent pas.');
      return;
    }
    this.chargement.set(true);
    this.erreur.set(null);
    this.auth.register(this.email, this.password).subscribe({
      next: () => this.router.navigateByUrl('/dashboard'),
      error: (e: HttpErrorResponse) => {
        this.chargement.set(false);
        this.erreur.set(
          e.error?.error ??
            (e.status === 409
              ? 'Cette adresse e-mail est déjà utilisée.'
              : "Inscription impossible. Réessayez."),
        );
      },
    });
  }
}
