import { Component, EventEmitter, Output, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { AuthDialogService } from '../../services/auth-dialog.service';

@Component({
  selector: 'app-register-dialog',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './register-dialog.component.html',
  styleUrl: './register-dialog.component.css'
})
export class RegisterDialogComponent {
  @Output() onClose = new EventEmitter<void>();
  @Output() onSuccess = new EventEmitter<void>();

  private readonly authService = inject(AuthService);
  private readonly authDialogService = inject(AuthDialogService);
  private readonly formBuilder = inject(FormBuilder);

  registerForm: FormGroup;
  errorMessage: string | null = null;
  isLoading = false;

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

  onSubmit(): void {
    if (this.registerForm.invalid) {
      this.errorMessage = 'Please fill in all fields correctly';
      return;
    }

    const { password, confirmPassword } = this.registerForm.value;
    if (password !== confirmPassword) {
      this.errorMessage = 'Passwords do not match';
      return;
    }

    this.isLoading = true;
    this.errorMessage = null;
    this.registerForm.disable();

    const { username, email, password: pwd } = this.registerForm.getRawValue();
    this.authService.register(username, pwd, email).subscribe({
      next: () => {
        this.isLoading = false;
        this.registerForm.enable();
        this.onSuccess.emit();
      },
      error: (err) => {
        this.isLoading = false;
        this.registerForm.enable();
        this.errorMessage =
          err.error?.message || 'Registration failed. Please try again.';
      }
    });
  }

  closeDialog(): void {
    this.onClose.emit();
  }

  openLogin(): void {
    this.authDialogService.openLogin();
  }
}
