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 { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { AuthApi, InviteDetails } from '../../../core/auth/auth-api';

@Component({
  selector: 'app-register',
  imports: [
    ReactiveFormsModule,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatInputModule,
    MatProgressSpinnerModule,
  ],
  templateUrl: './register.html',
  styleUrl: './register.scss',
})
export class Register {
  private readonly authApi = inject(AuthApi);
  private readonly formBuilder = inject(FormBuilder);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly token = this.route.snapshot.queryParamMap.get('token');

  protected readonly invitation = signal<InviteDetails | null>(null);
  protected readonly loadingInvitation = signal(true);
  protected readonly isSubmitting = signal(false);
  protected readonly errorMessage = signal<string | null>(null);

  protected readonly form = this.formBuilder.nonNullable.group({
    email: ['', [Validators.required, Validators.email]],
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    password: ['', [Validators.required, Validators.minLength(6)]],
    passwordConfirmation: ['', [Validators.required, Validators.minLength(6)]],
  });

  constructor() {
    if (!this.token) {
      this.loadingInvitation.set(false);
      this.errorMessage.set('Der Einladungslink ist unvollständig.');
      return;
    }

    this.authApi.verifyInvite(this.token).subscribe({
      next: (invitation) => {
        this.invitation.set(invitation);
        this.loadingInvitation.set(false);
      },
      error: () => {
        this.loadingInvitation.set(false);
        this.errorMessage.set('Der Einladungslink ist ungültig oder abgelaufen.');
      },
    });
  }

  protected onSubmit(): void {
    const invitation = this.invitation();
    const value = this.form.getRawValue();
    if (this.form.invalid || !invitation || this.isSubmitting()) return;
    if (value.password !== value.passwordConfirmation) {
      this.errorMessage.set('Die Passwörter stimmen nicht überein.');
      return;
    }

    this.isSubmitting.set(true);
    this.errorMessage.set(null);
    this.authApi
      .register({
        email: value.email,
        password: value.password,
        firstName: value.firstName,
        lastName: value.lastName,
        linkPlayerId: invitation.playerId,
      })
      .subscribe({
        next: () => {
          this.isSubmitting.set(false);
          void this.router.navigate(['/auth/login'], { replaceUrl: true });
        },
        error: () => {
          this.isSubmitting.set(false);
          this.errorMessage.set('Die Registrierung ist fehlgeschlagen.');
        },
      });
  }
}
