import { CurrencyPipe, DatePipe, registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { Component, LOCALE_ID, 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 { PublicTeamApi } from '../../core/team/public-team-api';
import { PlayerTransaction } from '../../models/transaction.model';
import { signedTransactionAmount } from '../../models/transaction-amount';
import { PublicPlayer as PublicPlayerModel } from '../../models/public-access.model';

registerLocaleData(localeDe);

@Component({
  selector: 'app-public-player',
  imports: [
    CurrencyPipe,
    DatePipe,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatIconModule,
    MatProgressSpinnerModule,
  ],
  providers: [{ provide: LOCALE_ID, useValue: 'de-DE' }],
  templateUrl: './public-player.html',
  styleUrl: './public-player.scss',
})
export class PublicPlayer {
  private readonly api = inject(PublicTeamApi);
  private readonly route = inject(ActivatedRoute);
  protected readonly token = this.route.snapshot.paramMap.get('token') ?? '';
  protected readonly player = signal<PublicPlayerModel | null>(null);
  protected readonly transactions = signal<PlayerTransaction[]>([]);
  protected readonly loading = signal(true);
  protected readonly notFound = signal(false);

  constructor() {
    const playerId = Number(this.route.snapshot.paramMap.get('playerId'));
    if (!this.token || !Number.isInteger(playerId) || playerId <= 0) {
      this.loading.set(false);
      this.notFound.set(true);
      return;
    }
    this.api.loadPlayerHistory(this.token, playerId).subscribe({
      next: (history) => {
        this.player.set(history.player);
        this.transactions.set(history.transactions);
        this.loading.set(false);
      },
      error: () => {
        this.loading.set(false);
        this.notFound.set(true);
      },
    });
  }

  protected typeLabel(transaction: PlayerTransaction): string {
    const type =
      typeof transaction.type === 'string' ? transaction.type : (transaction.type?.name ?? '');
    return (
      (
        {
          payment: 'Zahlung',
          credit: 'Guthaben',
          fine: 'Strafe',
          levy: 'Umlage',
          fee: 'Gebühr',
        } as Record<string, string>
      )[type] ?? type
    );
  }

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