import { Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { AuthApi } from '../../../core/auth/auth-api';

@Component({
  selector: 'app-reset-password',
  imports: [
    ReactiveFormsModule,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatInputModule,
  ],
  templateUrl: './reset-password.html',
  styleUrl: './reset-password.scss',
})
export class ResetPassword {
  private readonly authApi = inject(AuthApi);
  private readonly formBuilder = inject(FormBuilder);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly hash = this.route.snapshot.paramMap.get('hash');
  protected readonly submitting = signal(false);
  protected readonly errorMessage = signal<string | null>(null);
  protected readonly form = this.formBuilder.nonNullable.group({
    password: ['', [Validators.required, Validators.minLength(6)]],
    passwordConfirmation: ['', [Validators.required, Validators.minLength(6)]],
  });

  protected onSubmit(): void {
    const value = this.form.getRawValue();
    if (this.form.invalid || !this.hash || this.submitting()) return;
    if (value.password !== value.passwordConfirmation) {
      this.errorMessage.set('Die Passwörter stimmen nicht überein.');
      return;
    }
    this.submitting.set(true);
    this.authApi.resetPassword(this.hash, value.password).subscribe({
      next: () => {
        this.submitting.set(false);
        void this.router.navigate(['/auth/login'], { replaceUrl: true });
      },
      error: () => {
        this.submitting.set(false);
        this.errorMessage.set('Das Passwort konnte nicht geändert werden.');
      },
    });
  }
}
