import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from 'src/app/modules/auth.service';
import { TeamsService } from 'src/app/modules/teams/teams.service';
import { RegisterFormComponent } from './register-form/register-form.component';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

  private token: string | null= null;
  public teamInfo: { playerId: number, playerName: string, teamId: number, teamName: string} | undefined;
  error: boolean = false;

  constructor(private route: ActivatedRoute, private router: Router, private teamsService: TeamsService, private authService: AuthService, private snackBar: MatSnackBar) {}


  @ViewChild('formComponent') formComponent!: RegisterFormComponent;


  ngOnInit(): void {
    this.validateToken(this.route.snapshot.paramMap.get('token'));
    
 }

 private async validateToken(token: string | null) {

  if (!token) {
    return this.onNoTokenProvided();
  } else {
    this.teamsService.validateRegistrationToken(token).subscribe({
      next: data => { this.teamInfo = data; },
      error: () => { return this.onNoTokenProvided(); }
    });
  }

  this.token = token;
 }

 private onNoTokenProvided() {
  this.router.navigateByUrl('auth/register/no-token');
 }

 get registerForm() {
  return this.formComponent?.registerForm;
 }

 get registerFormInvalid(): boolean {
  return !this.registerForm || this.registerForm.invalid; 
 }

 register() {
  const data = this.registerForm.value as any;
  data.linkPlayerId = this.teamInfo?.playerId;

  this.authService.register(data).subscribe({
    next: () => { this.onPlayerRegistrationSuccess() },
    error: () => { this.onPlayerRegistrationFailure() }
  })
 }

 onPlayerRegistrationSuccess() {
  this.error = false;
  this.snackBar.open('Erfolgreich registriert', undefined, {
    duration: 5000
  });

  this.router.navigateByUrl('/auth')
 }

 onPlayerRegistrationFailure() {
  
  this.snackBar.open('Registrierung nicht möglich', undefined, {
    duration: 5000,
    panelClass: 'snackbar_error'
  });

  this.registerForm.reset()
 }

}
