import { Component, effect, inject, Input, output } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { UserViewModel } from '@app/adapters/users/user.presenter.model';
import { AuthFacade } from '@app/adapters/authentification/auth.facade';
import { ActionType } from '@app/domain/action-type.util';
import { ToastrService } from 'ngx-toastr';
import { LoadingComponent } from '@app/shared/components/loading/loading.component';
import { NgTemplateOutlet } from '@angular/common';

@Component({
  selector: 'app-user-password-form',
  standalone: true,
  imports: [ReactiveFormsModule, LoadingComponent, NgTemplateOutlet],
  templateUrl: './user-password-form.component.html',
  styleUrl: './user-password-form.component.scss',
})
export class UserPasswordFormComponent {
  private readonly toastrService = inject(ToastrService);
  @Input({ required: true }) user: UserViewModel | undefined = undefined;
  onFormSubmitted = output<any>();

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

  constructor() {
    let message = '';

    effect(() => {
      if (!this.loading().isLoading) {
        switch (this.loading().action) {
          case ActionType.CREATE:
            message = `Un mail de réinitialisation vous a été envoyé à cette adresse mail : ${this.user!.email}`;
            this.customToast(ActionType.CREATE, message);
            break;
        }
      }
    });
  }

  onSubmit() {
    this.authFacade.sendRequestPasswordReset(this.user!.email);
  }

  private customToast(action: ActionType, message: string): void {
    if (this.error().hasError) {
      this.toastrService.error(
        `Une erreur s'est produite, veuillez réessayer ulterieurement`,
        `Erreur`,
        {
          closeButton: true,
          progressAnimation: 'decreasing',
          progressBar: true,
        }
      );
      return;
    }

    this.toastrService.success(
      `${message}`,
      `${action === ActionType.CREATE ? 'Mise à jour' : ''}`,
      {
        closeButton: true,
        progressAnimation: 'decreasing',
        progressBar: true,
      }
    );
  }

  protected readonly ActionType = ActionType;
}
