import { CurrencyPipe, registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { Component, LOCALE_ID, computed, inject, signal } from '@angular/core';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { PublicTeamApi } from '../../core/team/public-team-api';
import { Penalty } from '../../models/penalty.model';
import { PublicTeamOverview } from '../../models/public-access.model';

registerLocaleData(localeDe);

@Component({
  selector: 'app-public-team',
  imports: [
    CurrencyPipe,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatProgressSpinnerModule,
  ],
  providers: [{ provide: LOCALE_ID, useValue: 'de-DE' }],
  templateUrl: './public-team.html',
  styleUrl: './public-team.scss',
})
export class PublicTeam {
  private readonly publicTeamApi = inject(PublicTeamApi);
  protected readonly token = inject(ActivatedRoute).snapshot.paramMap.get('token') ?? '';
  protected readonly team = signal<PublicTeamOverview | null>(null);
  protected readonly penalties = signal<Penalty[]>([]);
  protected readonly loading = signal(true);
  protected readonly notFound = signal(false);
  protected readonly search = signal('');
  protected readonly players = computed(() => {
    const query = this.search().trim().toLocaleLowerCase('de');
    return (this.team()?.players ?? [])
      .filter((player) => player.active)
      .filter((player) =>
        `${player.firstName} ${player.lastName}`.toLocaleLowerCase('de').includes(query),
      )
      .sort((a, b) => a.lastName.localeCompare(b.lastName, 'de'));
  });

  constructor() {
    if (!this.token) {
      this.loading.set(false);
      this.notFound.set(true);
      return;
    }
    this.publicTeamApi.loadTeam(this.token).subscribe({
      next: (team) => {
        this.team.set({
          ...team,
          balance: Number(team.balance),
          outstanding: Number(team.outstanding ?? 0),
        });
        this.penalties.set(team.penalties);
        this.loading.set(false);
      },
      error: () => {
        this.loading.set(false);
        this.notFound.set(true);
      },
    });
  }
}
