import { CurrencyPipe, registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { Component, LOCALE_ID, computed, 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 { MatSelectModule } from '@angular/material/select';
import { TeamPermissionsService } from '../../../core/team/team-permissions';
import { TeamStore } from '../../../core/team/team-store';
import { TeamsApi } from '../../../core/team/teams-api';
import { ContextHelp } from '../../../shared/context-help/context-help';

registerLocaleData(localeDe);

@Component({
  selector: 'app-members',
  imports: [
    CurrencyPipe,
    ReactiveFormsModule,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatSelectModule,
    ContextHelp,
  ],
  providers: [{ provide: LOCALE_ID, useValue: 'de-DE' }],
  templateUrl: './members.html',
  styleUrl: './members.scss',
})
export class Members {
  private readonly formBuilder = inject(FormBuilder);
  private readonly permissions = inject(TeamPermissionsService);
  private readonly teamsApi = inject(TeamsApi);
  private readonly teamStore = inject(TeamStore);
  protected readonly team = this.teamStore.team;
  protected readonly search = signal('');
  protected readonly showInactive = signal(false);
  protected readonly showCreateForm = signal(false);
  protected readonly saving = signal(false);
  protected readonly createForm = this.formBuilder.nonNullable.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    teamRole: [1, Validators.required],
  });

  protected readonly canManage = computed(() =>
    this.permissions.canDo(this.team(), 'memberManage'),
  );

  protected readonly players = computed(() => {
    const query = this.search().trim().toLocaleLowerCase('de');
    return (this.team()?.players ?? [])
      .filter((player) => this.showInactive() || player.active)
      .filter((player) =>
        `${player.firstName} ${player.lastName}`.toLocaleLowerCase('de').includes(query),
      )
      .sort((a, b) => a.lastName.localeCompare(b.lastName, 'de'));
  });

  protected createPlayer(): void {
    const team = this.team();
    if (!team || this.createForm.invalid || this.saving()) return;
    this.saving.set(true);
    this.teamsApi.createPlayer(team.id, this.createForm.getRawValue()).subscribe({
      next: () => {
        this.saving.set(false);
        this.showCreateForm.set(false);
        this.createForm.reset({ firstName: '', lastName: '', teamRole: 1 });
        this.teamStore.refreshTeam();
      },
      error: () => this.saving.set(false),
    });
  }

  protected roleName(role?: string): string {
    return (
      (
        {
          player: 'Spieler',
          scnd_treasurer: '2. Kassenwart',
          captain: 'Kapitän',
          treasurer: 'Kassenwart',
          coach: 'Trainer',
        } as Record<string, string>
      )[role ?? ''] ?? 'Spieler'
    );
  }
}
