import { CurrencyPipe, DatePipe, registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { Component, LOCALE_ID, computed, effect, inject, signal } from '@angular/core';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { TeamStore } from '../../../core/team/team-store';
import { TeamsApi } from '../../../core/team/teams-api';
import { PlayerTransaction } from '../../../models/transaction.model';
import { signedTransactionAmount } from '../../../models/transaction-amount';

registerLocaleData(localeDe);

@Component({
  selector: 'app-player-detail',
  imports: [
    CurrencyPipe,
    DatePipe,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatIconModule,
    MatProgressSpinnerModule,
  ],
  providers: [{ provide: LOCALE_ID, useValue: 'de-DE' }],
  templateUrl: './player-detail.html',
  styleUrl: './player-detail.scss',
})
export class PlayerDetail {
  private readonly route = inject(ActivatedRoute);
  private readonly teamsApi = inject(TeamsApi);
  private readonly teamStore = inject(TeamStore);
  private readonly playerId = Number(this.route.snapshot.paramMap.get('playerId'));
  private readonly loadedKey = signal<string | null>(null);
  protected readonly team = this.teamStore.team;
  protected readonly player = computed(
    () => this.team()?.players?.find((player) => player.id === this.playerId) ?? null,
  );
  protected readonly transactions = signal<PlayerTransaction[]>([]);
  protected readonly loading = signal(true);

  constructor() {
    effect(() => {
      const team = this.team();
      if (!team || !Number.isInteger(this.playerId)) return;
      const key = `${team.id}:${this.playerId}`;
      if (this.loadedKey() === key) return;
      this.loadedKey.set(key);
      this.teamsApi.loadPlayerTransactions(team.id, this.playerId).subscribe({
        next: (transactions) => {
          this.transactions.set(transactions);
          this.loading.set(false);
        },
        error: () => this.loading.set(false),
      });
    });
  }

  protected typeName(transaction: PlayerTransaction): string {
    return typeof transaction.type === 'string'
      ? transaction.type
      : (transaction.type?.name ?? 'Buchung');
  }

  protected displayAmount(transaction: PlayerTransaction): number {
    return signedTransactionAmount(transaction.amount, transaction.type);
  }
}
