import { Component, computed, effect, inject, signal } from '@angular/core';
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 { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { TeamPermissionsApi } from '../../../../core/team/team-permissions-api';
import { TeamPermissionsService } from '../../../../core/team/team-permissions';
import { TeamStore } from '../../../../core/team/team-store';
import { TeamPermissions } from '../../../../models/team-permissions.model';
import { ContextHelp } from '../../../../shared/context-help/context-help';

interface PermissionField {
  key: keyof TeamPermissions;
  label: string;
}

const FIELDS: PermissionField[] = [
  { key: 'transactionCreateMinRole', label: 'Buchung erfassen' },
  { key: 'transactionReverseMinRole', label: 'Buchung stornieren' },
  { key: 'inviteMinRole', label: 'Mitglieder einladen' },
  { key: 'memberManageMinRole', label: 'Mitglieder verwalten' },
  { key: 'penaltyManageMinRole', label: 'Strafenkatalog verwalten' },
  { key: 'publicAccessManageMinRole', label: 'Öffentliche Freigabe verwalten' },
];

const ROLE_OPTIONS = [
  { id: 1, label: 'Spieler' },
  { id: 2, label: '2. Kassenwart' },
  { id: 3, label: 'Kapitän' },
  { id: 4, label: 'Kassenwart' },
  { id: 5, label: 'Trainer' },
];

@Component({
  selector: 'app-permissions',
  imports: [
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatSelectModule,
    MatSnackBarModule,
    ContextHelp,
  ],
  templateUrl: './permissions.html',
  styleUrl: './permissions.scss',
})
export class Permissions {
  private readonly api = inject(TeamPermissionsApi);
  private readonly permissions = inject(TeamPermissionsService);
  private readonly snackBar = inject(MatSnackBar);
  private readonly teamStore = inject(TeamStore);
  private loadedTeamId: number | null = null;

  protected readonly team = this.teamStore.team;
  protected readonly fields = FIELDS;
  protected readonly roleOptions = ROLE_OPTIONS;
  protected readonly loading = signal(true);
  protected readonly saving = signal(false);
  protected readonly loadFailed = signal(false);
  protected readonly values = signal<TeamPermissions | null>(null);
  protected readonly canManage = computed(() =>
    this.permissions.canDo(this.team(), 'memberManage'),
  );

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

  protected changeRole(field: keyof TeamPermissions, roleId: number): void {
    const teamId = this.team()?.id;
    const current = this.values();
    if (!this.canManage() || !teamId || !current || this.saving() || current[field] === roleId) {
      return;
    }
    this.saving.set(true);
    this.api.updatePermissions(teamId, { [field]: roleId }).subscribe({
      next: (updated) => {
        this.saving.set(false);
        this.values.set(updated);
        this.teamStore.refreshTeam();
        this.snackBar.open('Berechtigung wurde gespeichert.', undefined, { duration: 4000 });
      },
      error: () => {
        this.saving.set(false);
        this.snackBar.open('Berechtigung konnte nicht gespeichert werden.', undefined, {
          duration: 5000,
        });
      },
    });
  }

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

  private load(teamId: number): void {
    this.loading.set(true);
    this.loadFailed.set(false);
    this.api.getPermissions(teamId).subscribe({
      next: (values) => {
        this.loading.set(false);
        this.values.set(values);
      },
      error: () => {
        this.loading.set(false);
        this.loadFailed.set(true);
      },
    });
  }
}
