import { Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { Team } from '../../../models/team.model';
import { TeamsApi } from '../../../core/team/teams-api';

@Component({
  selector: 'app-create-team-dialog',
  imports: [ReactiveFormsModule, MatButtonModule, MatDialogModule, MatFormFieldModule, MatInputModule],
  template: `
    <h2 mat-dialog-title>Team erstellen</h2>
    <form [formGroup]="form" (ngSubmit)="submit()">
      <mat-dialog-content>
        <mat-form-field appearance="outline" class="full-width">
          <mat-label>Teamname</mat-label>
          <input matInput formControlName="name" />
        </mat-form-field>
      </mat-dialog-content>
      <mat-dialog-actions align="end">
        <button mat-button type="button" (click)="dialogRef.close()">Abbrechen</button>
        <button mat-flat-button type="submit" [disabled]="form.invalid || saving()">
          Erstellen
        </button>
      </mat-dialog-actions>
    </form>
  `,
  styles: [
    `
      .full-width {
        width: 100%;
      }
    `,
  ],
})
export class CreateTeamDialog {
  protected readonly dialogRef = inject(MatDialogRef<CreateTeamDialog, Team | undefined>);
  private readonly formBuilder = inject(FormBuilder);
  private readonly teamsApi = inject(TeamsApi);

  protected readonly saving = signal(false);
  protected readonly form = this.formBuilder.nonNullable.group({
    name: ['', Validators.required],
  });

  protected submit(): void {
    if (this.form.invalid || this.saving()) return;
    this.saving.set(true);
    this.teamsApi.createTeam(this.form.getRawValue()).subscribe({
      next: (team) => {
        this.saving.set(false);
        this.dialogRef.close(team);
      },
      error: () => this.saving.set(false),
    });
  }
}
