import { Component, EventEmitter, Output, signal, inject } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { RegisterRequest } from '../../../model/auth/RegisterRequest';
import { AuthService } from '@service/auth.service';
import { CommonModule } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './register.component.html',
})
export class RegisterComponent {
  registerForm: FormGroup;
  errorMessage = signal<string>('');
  isLoading = signal<boolean>(false);
  fieldErrors = signal<Record<string, string>>({});
  @Output() switchForm = new EventEmitter<void>();
  @Output() closeDialog = new EventEmitter<void>();

  private fb = inject(FormBuilder);
  private authService = inject(AuthService);

  constructor() {
    this.registerForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      username: ['', [Validators.required, Validators.minLength(3)]],
      password: ['', [Validators.required, Validators.minLength(6)]],
    });
  }

  get form() {
    return this.registerForm.controls;
  }

  switchToLogin(): void {
    this.switchForm.emit();
  }

  onSubmit(): void {
    if (this.registerForm.invalid) {
      return;
    }

    this.isLoading.set(true);
    this.errorMessage.set('');
    this.fieldErrors.set({});

    const registerRequest: RegisterRequest = {
      email: this.form['email'].value,
      username: this.form['username'].value,
      password: this.form['password'].value,
    };

    this.authService.register(registerRequest).subscribe({
      next: () => {
        this.isLoading.set(false);
        this.closeDialog.emit();
        this.switchToLogin();
      },
      error: (err: HttpErrorResponse) => {
        this.isLoading.set(false);

        if (err.status === 409) {
          const message = err.error?.message;
          switch (message) {
            case 'Email is already in use':
              this.fieldErrors.update((errors) => ({
                ...errors,
                email: 'Diese E-Mail-Adresse wird bereits verwendet.',
              }));
              break;
            case 'Username is already taken':
              this.fieldErrors.update((errors) => ({
                ...errors,
                username: 'Dieser Benutzername ist bereits vergeben.',
              }));
              break;
          }
        } else {
          this.errorMessage.set(err.error?.message || 'Failed to register. Please try again.');
        }
      },
    });
  }
}
