import { Component, 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 { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { AuthApi } from '../../../../core/auth/auth-api';
import { AuthStore } from '../../../../core/auth/auth-store';
import { TeamStore } from '../../../../core/team/team-store';

@Component({
  selector: 'app-invite',
  imports: [
    ReactiveFormsModule,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatSelectModule,
    MatSnackBarModule,
  ],
  templateUrl: './invite.html',
  styleUrl: './invite.scss',
})
export class Invite {
  private readonly authApi = inject(AuthApi);
  private readonly authStore = inject(AuthStore);
  private readonly formBuilder = inject(FormBuilder);
  private readonly snackBar = inject(MatSnackBar);
  private readonly teamStore = inject(TeamStore);
  protected readonly team = this.teamStore.team;
  protected readonly inviteLink = signal('');
  protected readonly loading = signal(false);
  protected readonly form = this.formBuilder.nonNullable.group({
    playerId: [0, [Validators.required, Validators.min(1)]],
  });
  protected readonly availablePlayers = computed(() =>
    (this.team()?.players ?? []).filter((player) => player.active && !player.user),
  );
  protected readonly canInvite = 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 generateLink(): void {
    const team = this.team();
    const player = this.availablePlayers().find(
      (item) => item.id === this.form.controls.playerId.value,
    );
    if (!this.canInvite() || !team || !player || this.form.invalid || this.loading()) return;
    this.loading.set(true);
    this.authApi
      .createInvite({
        teamId: team.id,
        teamName: team.name,
        playerId: player.id,
        playerName: `${player.firstName} ${player.lastName}`,
      })
      .subscribe({
        next: ({ token }) => {
          this.inviteLink.set(
            `${location.origin}/auth/register?token=${encodeURIComponent(token)}`,
          );
          this.loading.set(false);
        },
        error: () => this.loading.set(false),
      });
  }

  protected async copyLink(): Promise<void> {
    if (!this.inviteLink()) return;
    try {
      await navigator.clipboard.writeText(this.inviteLink());
      this.snackBar.open('Einladungslink wurde kopiert.', undefined, { duration: 4000 });
    } catch {
      this.snackBar.open('Link konnte nicht kopiert werden.', undefined, { duration: 5000 });
    }
  }
}
