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

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [RouterLink, ProgressBarModule, ReactiveFormsModule, BtnLoadingComponent],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './login.component.html',
  styleUrl: './login.component.scss',
})
@UntilDestroy()
export class LoginComponent {
  private readonly facade = inject(AuthFacade);

  private formBuilder = inject(FormBuilder);

  loginForm = this.formBuilder.group({
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', Validators.required),
  });

  formSubmitted = output<any>();

  protected readonly router = inject(Router);
  private readonly authResponse = this.facade.authResponse;
  protected readonly loading = this.facade.loading;
  protected readonly error = this.facade.error;

  constructor() {
    effect(() => {
      if (!this.loading().isLoading) {
        switch (this.loading().action) {
          case ActionType.READ:
            if (this.error().hasError) {
              this.loginForm.enable();
              this.loginForm.markAllAsTouched();
              this.loginForm.markAsDirty();
              return;
            }
            this.router
              .navigate(['/my-profile'], { state: { user: this.authResponse()!.record } })
              .then(() => {});
            break;
        }
      }
    });
  }

  onSubmit() {
    if (this.loginForm.invalid) {
      this.loginForm.markAllAsTouched();
      this.loginForm.markAsDirty();
      return;
    }
    this.loginForm.disable();

    const data = this.loginForm.getRawValue() as LoginDto;

    this.formSubmitted.emit(data);

    this.facade.login(data);
  }
}
