import { Component, effect, inject } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { MatListModule } from '@angular/material/list';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { AuthStore } from '../../core/auth/auth-store';
import { MyTeamsStore } from '../../core/team/my-teams-store';

@Component({
  selector: 'app-team-select',
  imports: [RouterLink, MatListModule, MatProgressSpinnerModule],
  templateUrl: './team-select.html',
  styleUrl: './team-select.scss',
})
export class TeamSelect {
  private readonly authStore = inject(AuthStore);
  private readonly myTeamsStore = inject(MyTeamsStore);
  private readonly router = inject(Router);

  protected readonly players = this.myTeamsStore.players;
  protected readonly loading = this.myTeamsStore.loading;

  constructor() {
    const userId = this.authStore.currentUser()?.id;
    if (userId) {
      this.myTeamsStore.ensureLoaded(userId);
    }

    effect(() => {
      const players = this.myTeamsStore.players();
      if (!this.myTeamsStore.loading() && players.length === 1 && players[0].team) {
        void this.router.navigate(['/team', players[0].team.id, 'overview'], {
          replaceUrl: true,
        });
      }
    });
  }
}
