import { CurrencyPipe, DatePipe, registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { Component, LOCALE_ID, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
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 { TransactionsApi } from '../../../core/team/transactions-api';
import { TeamActivity } from '../../../models/transaction.model';
import { signedTransactionAmount } from '../../../models/transaction-amount';
import { of } from 'rxjs';
import { catchError, distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';

registerLocaleData(localeDe);

@Component({
  selector: 'app-overview',
  imports: [CurrencyPipe, DatePipe, MatCardModule, MatIconModule, MatProgressSpinnerModule],
  providers: [{ provide: LOCALE_ID, useValue: 'de-DE' }],
  templateUrl: './overview.html',
  styleUrl: './overview.scss',
})
export class Overview {
  private readonly route = inject(ActivatedRoute);
  private readonly transactionsApi = inject(TransactionsApi);
  protected readonly team = inject(TeamStore).team;
  protected readonly activities = signal<TeamActivity[]>([]);
  protected readonly loadingActivities = signal(true);

  constructor() {
    const parentRoute = this.route.parent;
    if (!parentRoute) {
      this.loadingActivities.set(false);
      return;
    }

    parentRoute.paramMap
      .pipe(
        map((params) => Number(params.get('id'))),
        distinctUntilChanged(),
        tap((id) => {
          this.activities.set([]);
          this.loadingActivities.set(Number.isInteger(id) && id > 0);
        }),
        switchMap((id) =>
          Number.isInteger(id) && id > 0
            ? this.transactionsApi.loadTeamTransactions(id).pipe(catchError(() => of([])))
            : of([]),
        ),
        takeUntilDestroyed(),
      )
      .subscribe((activities) => {
        this.activities.set(activities.slice(0, 10));
        this.loadingActivities.set(false);
      });
  }

  protected activityIcon(activity: TeamActivity): string {
    return activity.isTeamWalletTransaction ? 'account_balance' : 'person';
  }

  protected displayAmount(activity: TeamActivity): number {
    return signedTransactionAmount(activity.amount, activity.type);
  }
}
