import { Component, effect, inject, input } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { ProfileViewModel } from '@app/adapters/profiles/profile.presenter.model';
import { ProfileFacade } from '@app/adapters/profiles/profile.facade';
import { ActionType } from '@app/domain/action-type.util';
import { Profile } from '@app/domain/profiles/profile.model';
import { LoadingComponent } from '@app/shared/components/loading/loading.component';
import { FileManagerService } from '@app/adapters/shared/services/file-manager.service';

@Component({
  selector: 'app-my-profile-update-cv-form',
  standalone: true,
  imports: [LoadingComponent, NgTemplateOutlet],
  templateUrl: './my-profile-update-cv-form.component.html',
  styleUrl: './my-profile-update-cv-form.component.scss',
})
export class MyProfileUpdateCvFormComponent {
  readonly fileManagerService = inject(FileManagerService);
  profile = input.required<ProfileViewModel>();

  file = this.fileManagerService.file; // Variable to store file
  fileError = this.fileManagerService.fileError;

  private readonly profileFacade = inject(ProfileFacade);

  readonly loading = this.profileFacade.loading;
  readonly error = this.profileFacade.error;

  constructor() {
    effect(() => {
      switch (this.loading().action) {
        case ActionType.UPDATE:
          if (!this.loading().isLoading && !this.error().hasError) {
            this.fileManagerService.resetFile();
          }
          break;
      }
    });
  }

  onSubmit(): void {
    const file = this.file();

    if (file && !this.fileError()) {
      const formData = new FormData();
      formData.append('cv', file);
      this.profileFacade.update(this.profile()?.id!, formData as Partial<Profile>);
    }
  }

  get canSubmit(): boolean {
    return (
      this.file() != null &&
      !this.fileError() &&
      !this.error().hasError &&
      !this.loading().isLoading
    );
  }
}
