import { Component } from '@angular/core';
import { AuthService } from '../authService/auth.service';
import { LoadingSpinnerComponent } from '../../shared/loading-spinner/loading-spinner.component';
import { CommonModule } from '@angular/common';
import { from, map, switchMap } from 'rxjs';
import { PendingActionsService } from '../../score/pending-actions.service';
import { UserService } from '../../user-profile/user.service';
import { ActivatedRoute, Router } from '@angular/router';
import { User } from '../model/user.model';

@Component({
  selector: 'app-finish-signup',
  standalone: true,
  templateUrl: './finish-signup.component.html',
  styleUrl: './finish-signup.component.css',
  imports: [LoadingSpinnerComponent, CommonModule],
})
export class FinishSignupComponent {
  isLoading = false;
  constructor(
    private authService: AuthService,
    private pendingService: PendingActionsService,
    private userService: UserService,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.isLoading = true;
    this.authService
      .loginWithEmail()
      .pipe(
        switchMap(async (newUser: User) => {
          const addUser$ = from(this.userService.addUser(newUser));
          return addUser$;
        })
      )
      .subscribe({
        next: () => {
          this.route.queryParams.subscribe((params) => {
            const score = params['score'];
            const uid = params['uid'];
            if (score && uid) {
              this.router.navigate(['/user-profile'], {
                queryParams: {
                  score: score,
                  uid: uid,
                },
              });
            } else {
              this.router.navigate(['/score-table']);
            }
          });
          this.isLoading = false;
        },
        error: (err) => {
          console.error('Error:', err);
          this.isLoading = false;
        },
      });
  }

  ngOnDestroy() {
    this.isLoading = false;
  }
}
