import {Component} from '@angular/core';
import {MatDialogActions, MatDialogContent, MatDialogRef, MatDialogTitle} from '@angular/material/dialog';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {MatButtonModule} from '@angular/material/button';
import {MatInputModule} from '@angular/material/input';
import {MatFormFieldModule} from '@angular/material/form-field';

import {MatSnackBar} from '@angular/material/snack-bar';
import {AuthService} from '@services/auth.service';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    MatButtonModule,
    MatInputModule,
    MatFormFieldModule,
    MatDialogTitle,
    MatDialogContent,
    MatDialogActions
],
  templateUrl: './login.component.html',
  styleUrl: './login.component.scss'
})
export class LoginDialogComponent {
  public loginForm: FormGroup;

  constructor(
    public dialogRef: MatDialogRef<LoginDialogComponent>,
    private fb: FormBuilder,
    private authService: AuthService,
    private snackBar: MatSnackBar
  ) {
    this.loginForm = this.fb.group({
      code: ['', [
        Validators.required,
        Validators.minLength(8),
        Validators.maxLength(8),
        Validators.pattern('^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]+$')
      ]]
    });
  }

  onCancel(): void {
    this.dialogRef.close();
  }

  onSubmit(): void {
    if (!this.loginForm.valid) {
      this.snackBar.open('Invalid code', '', {duration: 2000});
      return;
    }
    this.snackBar.open('Logging in...', '', {duration: 2000});
    this.authService.login(this.loginForm.value.code).subscribe({
      next: (jwt) => {
        this.dialogRef.close(jwt);
      },
      error: () => {
        this.loginForm.get('code')?.setErrors({
          invalid: true
        });
      }
    });
  }

  onKeyUp(): void {
    this.loginForm.patchValue({'code': this.loginForm.get('code')?.value.toUpperCase()})
  }
}
