import { Component, effect, inject, Input } from '@angular/core';
import { AuthService } from '@app/core/services/authentication/auth.service';
import { NgClass } from '@angular/common';
import { ToastrService } from 'ngx-toastr';
import { ProfileViewModel } from '@app/ui/profiles/profile.presenter.model';
import { ProfileFacade } from '@app/ui/profiles/profile.facade';
import { ActionType } from '@app/domain/action-type.util';
import { Profile } from '@app/domain/profiles/profile.model';

@Component({
  selector: 'app-my-profile-update-cv-form',
  standalone: true,
  imports: [NgClass],
  templateUrl: './my-profile-update-cv-form.component.html',
  styleUrl: './my-profile-update-cv-form.component.scss',
})
export class MyProfileUpdateCvFormComponent {
  @Input({ required: true }) profile: ProfileViewModel | undefined = undefined;

  private readonly toastrService = inject(ToastrService);

  private readonly authService = inject(AuthService);

  file: File | null = null; // Variable to store file

  private readonly profileFacade = new ProfileFacade();
  protected readonly loading = this.profileFacade.loading;
  protected readonly error = this.profileFacade.error;

  constructor() {
    effect(() => {
      switch (this.loading().action) {
        case ActionType.UPDATE:
          if (!this.loading() && !this.error().hasError) {
            this.authService.updateUser();

            this.toastrService.success(` Votre CV a bien été modifier !`, `Mise à jour`, {
              closeButton: true,
              progressAnimation: 'decreasing',
              progressBar: true,
            });
          }
      }
    });
  }

  onSubmit() {
    if (this.file != null) {
      const formData = new FormData();
      formData.append('cv', this.file); // "avatar" est le nom du champ dans PocketBase
      this.profileFacade.update(this.profile?.id!, formData as Partial<Profile>);
    }
  }

  onFileChange($event: Event) {
    const target: HTMLInputElement = $event.target as HTMLInputElement;
    if (target?.files?.[0]) {
      this.file = target.files[0];
    }
  }
}
