import { CurrencyPipe, registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { HttpErrorResponse } from '@angular/common/http';
import { Component, DestroyRef, LOCALE_ID, computed, effect, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDialog } from '@angular/material/dialog';
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 { Router, RouterLink } from '@angular/router';
import { EMPTY, Observable, catchError, finalize, switchMap, take, tap } from 'rxjs';
import { TeamPermissionsService } from '../../../../core/team/team-permissions';
import { PenaltyApi } from '../../../../core/team/penalty-api';
import { TeamStore } from '../../../../core/team/team-store';
import { Penalty } from '../../../../models/penalty.model';
import { ConfirmDialog } from '../../../../shared/confirm-dialog/confirm-dialog';
import { ContextHelp } from '../../../../shared/context-help/context-help';

registerLocaleData(localeDe);

@Component({
  selector: 'app-penalties',
  imports: [
    CurrencyPipe,
    ReactiveFormsModule,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatProgressSpinnerModule,
    ContextHelp,
  ],
  providers: [{ provide: LOCALE_ID, useValue: 'de-DE' }],
  templateUrl: './penalties.html',
  styleUrl: './penalties.scss',
})
export class Penalties {
  private readonly destroyRef = inject(DestroyRef);
  private readonly dialog = inject(MatDialog);
  private readonly formBuilder = inject(FormBuilder);
  private readonly penaltyApi = inject(PenaltyApi);
  private readonly permissions = inject(TeamPermissionsService);
  private readonly router = inject(Router);
  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 pendingPenaltyId = signal<number | null>(null);
  protected readonly editingPenaltyId = signal<number | null>(null);
  protected readonly loadError = signal<string | null>(null);
  protected readonly mutationError = signal<string | null>(null);
  protected readonly mutationPending = computed(
    () => this.saving() || this.pendingPenaltyId() !== null,
  );
  protected readonly search = signal('');
  protected readonly form = this.formBuilder.nonNullable.group({
    description: ['', [Validators.required, Validators.maxLength(120), Validators.pattern(/\S/)]],
    amount: [
      0,
      [
        Validators.required,
        Validators.min(0.01),
        Validators.max(10000),
        Validators.pattern(/^\d+(\.\d{1,2})?$/),
      ],
    ],
  });
  protected readonly editForm = this.formBuilder.nonNullable.group({
    description: ['', [Validators.required, Validators.maxLength(120), Validators.pattern(/\S/)]],
    amount: [
      0,
      [
        Validators.required,
        Validators.min(0.01),
        Validators.max(10000),
        Validators.pattern(/^\d+(\.\d{1,2})?$/),
      ],
    ],
  });
  protected readonly canManage = computed(() =>
    this.permissions.canDo(this.team(), 'penaltyManage'),
  );
  protected readonly canBook = computed(() =>
    this.permissions.canDo(this.team(), 'transactionCreate'),
  );
  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.mutationPending()) return;
    this.saving.set(true);
    this.mutationError.set(null);
    this.penaltyApi
      .createPenalty({ teamId: team.id, ...this.form.getRawValue() })
      .pipe(
        tap(() => this.form.reset({ description: '', amount: 0 })),
        switchMap(() => this.reloadAfterMutation(team.id)),
        finalize(() => this.saving.set(false)),
        takeUntilDestroyed(this.destroyRef),
      )
      .subscribe({
        next: (penalties) => {
          this.penalties.set(penalties);
        },
        error: (error: HttpErrorResponse) =>
          this.mutationError.set(this.errorMessage(error, 'Eintrag konnte nicht angelegt werden.')),
      });
  }

  protected startEdit(penalty: Penalty): void {
    if (!this.canManage() || this.mutationPending()) return;
    this.editingPenaltyId.set(penalty.id);
    this.editForm.setValue({ description: penalty.description, amount: penalty.amount });
    this.mutationError.set(null);
  }

  protected cancelEdit(): void {
    if (this.pendingPenaltyId() !== null) return;
    this.editingPenaltyId.set(null);
    this.mutationError.set(null);
  }

  protected savePenalty(penalty: Penalty): void {
    const teamId = this.team()?.id;
    if (
      !this.canManage() ||
      !teamId ||
      this.editingPenaltyId() !== penalty.id ||
      this.editForm.invalid ||
      this.mutationPending()
    ) {
      return;
    }
    this.pendingPenaltyId.set(penalty.id);
    this.mutationError.set(null);
    this.penaltyApi
      .updatePenalty(penalty.id, this.editForm.getRawValue())
      .pipe(
        tap(() => this.editingPenaltyId.set(null)),
        switchMap(() => this.reloadAfterMutation(teamId)),
        finalize(() => this.pendingPenaltyId.set(null)),
        takeUntilDestroyed(this.destroyRef),
      )
      .subscribe({
        next: (penalties) => {
          this.penalties.set(penalties);
        },
        error: (error: HttpErrorResponse) =>
          this.mutationError.set(
            this.errorMessage(error, 'Eintrag konnte nicht gespeichert werden.'),
          ),
      });
  }

  protected confirmDelete(penalty: Penalty): void {
    if (!this.canManage() || this.mutationPending()) return;
    this.dialog
      .open(ConfirmDialog, {
        data: {
          title: 'Eintrag löschen?',
          message: `„${penalty.description}“ wird endgültig aus dem Strafenkatalog gelöscht.`,
          confirmLabel: 'Löschen',
        },
        restoreFocus: true,
      })
      .afterClosed()
      .pipe(take(1), takeUntilDestroyed(this.destroyRef))
      .subscribe((confirmed) => {
        if (confirmed) this.deletePenalty(penalty);
      });
  }

  protected bookPenalty(penalty: Penalty): void {
    const teamId = this.team()?.id;
    if (!teamId) return;
    void this.router.navigate(['/team', teamId, 'cashbox'], {
      queryParams: { penaltyId: penalty.id },
    });
  }

  protected retryLoad(): void {
    const teamId = this.team()?.id;
    if (teamId) this.load(teamId);
  }

  private deletePenalty(penalty: Penalty): void {
    const teamId = this.team()?.id;
    if (!teamId) return;
    this.pendingPenaltyId.set(penalty.id);
    this.mutationError.set(null);
    this.penaltyApi
      .deletePenalty(penalty.id)
      .pipe(
        switchMap(() => this.reloadAfterMutation(teamId)),
        finalize(() => this.pendingPenaltyId.set(null)),
        takeUntilDestroyed(this.destroyRef),
      )
      .subscribe({
        next: (penalties) => {
          this.penalties.set(penalties);
          if (this.editingPenaltyId() === penalty.id) this.editingPenaltyId.set(null);
        },
        error: (error: HttpErrorResponse) =>
          this.mutationError.set(this.errorMessage(error, 'Eintrag konnte nicht gelöscht werden.')),
      });
  }

  private reloadAfterMutation(teamId: number): Observable<Penalty[]> {
    return this.penaltyApi.loadPenalties(teamId).pipe(
      catchError(() => {
        this.loadError.set(
          'Änderung wurde gespeichert, aber der Katalog konnte nicht aktualisiert werden.',
        );
        return EMPTY;
      }),
    );
  }

  private load(teamId: number): void {
    this.loading.set(true);
    this.loadError.set(null);
    this.penaltyApi
      .loadPenalties(teamId)
      .pipe(
        finalize(() => this.loading.set(false)),
        takeUntilDestroyed(this.destroyRef),
      )
      .subscribe({
        next: (penalties) => this.penalties.set(penalties),
        error: () => {
          this.penalties.set([]);
          this.loadError.set('Katalog konnte nicht geladen werden.');
        },
      });
  }

  private errorMessage(error: HttpErrorResponse, fallback: string): string {
    const detail = typeof error.error?.message === 'string' ? error.error.message : '';
    if (error.status === 403) return 'Keine Berechtigung für diese Änderung.';
    if (error.status === 404)
      return 'Der Eintrag wurde nicht gefunden. Bitte lade den Katalog neu.';
    if (error.status === 409) return detail || 'Diese Beschreibung existiert bereits.';
    if (error.status === 422) return 'Bitte prüfe Beschreibung und Betrag.';
    return detail || fallback;
  }
}
