import { ChangeDetectionStrategy, Component, effect, inject, output } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { FormBuilder, FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { RegisterDto } from '@app/domain/authentification/dto/register-dto';
import { UntilDestroy } from '@ngneat/until-destroy';
import { ProgressBarModule } from 'primeng/progressbar';
import { ActionType } from '@app/domain/action-type.util';
import { AuthFacade } from '@app/adapters/authentification/auth.facade';
import { BtnLoadingComponent } from '@app/shared/components/btn-loading/btn-loading.component';

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [RouterLink, ReactiveFormsModule, ProgressBarModule, BtnLoadingComponent],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './register.component.html',
  styleUrl: './register.component.scss',
})
@UntilDestroy()
export class RegisterComponent {
  private readonly formBuilder = inject(FormBuilder);
  private readonly router = inject(Router);
  protected registerForm = this.formBuilder.group({
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', [Validators.required, Validators.minLength(8)]),
    passwordConfirm: new FormControl('', [Validators.required, Validators.minLength(8)]),
  });

  formSubmitted = output<any>();

  private readonly authFacade = inject(AuthFacade);
  protected readonly authLoading = this.authFacade.loading;
  protected readonly authError = this.authFacade.error;
  protected readonly isVerificationEmailSent = this.authFacade.isVerificationEmailSent;

  constructor() {
    effect(() => {
      switch (this.authLoading().action) {
        case ActionType.CREATE:
          if (
            !this.authLoading().isLoading &&
            !this.authError().hasError &&
            this.isVerificationEmailSent()
          ) {
            if (this.authError().hasError) {
              this.registerForm.enable();
              return;
            }
            this.router.navigate(['/auth']).then(() => {});
          }
          break;
      }
    });
  }

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

    if (
      this.registerForm.get('password')?.value !== this.registerForm.get('passwordConfirm')?.value
    ) {
      this.registerForm.get('passwordConfirm')?.setErrors({ passwordMismatch: true });
      return;
    }

    this.registerForm.disable();

    const data = this.registerForm.getRawValue() as RegisterDto;
    this.formSubmitted.emit(data);

    this.authFacade.register(data);
  }
}
