import { CurrencyPipe, registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { Component, LOCALE_ID, computed, effect, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { 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 { AuthStore } from '../../../../core/auth/auth-store';
import { PenaltyApi } from '../../../../core/team/penalty-api';
import { TeamStore } from '../../../../core/team/team-store';
import { Penalty } from '../../../../models/penalty.model';

registerLocaleData(localeDe);

@Component({
  selector: 'app-penalties',
  imports: [
    CurrencyPipe,
    ReactiveFormsModule,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatProgressSpinnerModule,
  ],
  providers: [{ provide: LOCALE_ID, useValue: 'de-DE' }],
  templateUrl: './penalties.html',
  styleUrl: './penalties.scss',
})
export class Penalties {
  private readonly authStore = inject(AuthStore);
  private readonly formBuilder = inject(FormBuilder);
  private readonly penaltyApi = inject(PenaltyApi);
  private readonly teamStore = inject(TeamStore);
  private loadedTeamId: number | null = null;
  protected readonly team = this.teamStore.team;
  protected readonly penalties = signal<Penalty[]>([]);
  protected readonly loading = signal(false);
  protected readonly saving = signal(false);
  protected readonly search = signal('');
  protected readonly form = this.formBuilder.nonNullable.group({
    description: ['', Validators.required],
    amount: [0, [Validators.required, Validators.min(0.01), Validators.max(10000)]],
  });
  protected readonly canManage = computed(() => {
    const user = this.authStore.currentUser();
    if (user?.role?.id === 1) return true;
    return (
      this.team()?.players?.some(
        (player) => player.user?.id === user?.id && (player.teamRole?.id ?? 0) > 2,
      ) ?? false
    );
  });
  protected readonly filteredPenalties = computed(() => {
    const query = this.search().trim().toLocaleLowerCase('de');
    return this.penalties().filter((penalty) =>
      penalty.description.toLocaleLowerCase('de').includes(query),
    );
  });

  constructor() {
    effect(() => {
      const teamId = this.team()?.id;
      if (teamId && teamId !== this.loadedTeamId) {
        this.loadedTeamId = teamId;
        this.load(teamId);
      }
    });
  }

  protected createPenalty(): void {
    const team = this.team();
    if (!this.canManage() || !team || this.form.invalid || this.saving()) return;
    this.saving.set(true);
    this.penaltyApi.createPenalty({ teamId: team.id, ...this.form.getRawValue() }).subscribe({
      next: (penalty) => {
        this.penalties.update((items) => [...items, penalty]);
        this.form.reset({ description: '', amount: 0 });
        this.saving.set(false);
      },
      error: () => this.saving.set(false),
    });
  }

  private load(teamId: number): void {
    this.loading.set(true);
    this.penaltyApi.loadPenalties(teamId).subscribe({
      next: (penalties) => {
        this.penalties.set(penalties);
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }
}
