import { Component, effect, inject, input, output, signal } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { environment } from '@env/environment';
import { ProjectViewModel } from '@app/adapters/projects/project.presenter.model';
import { ProjectFacade } from '@app/adapters/projects/project.facade';
import { ActionType } from '@app/domain/action-type.util';
import { LoadingComponent } from '@app/shared/components/loading/loading.component';
import { FileManagerService } from '@app/adapters/shared/services/file-manager.service';

@Component({
  selector: 'app-project-picture-form',
  standalone: true,
  imports: [LoadingComponent, NgTemplateOutlet],
  templateUrl: './project-picture-form.component.html',
  styleUrl: './project-picture-form.component.scss',
})
export class ProjectPictureFormComponent {
  project = input.required<ProjectViewModel | undefined>();
  protected readonly environment = environment;
  protected readonly ActionType = ActionType;
  protected readonly fileManagerService = inject(FileManagerService);

  onFormSubmitted = output<any>();

  private readonly projectFacade = inject(ProjectFacade);
  protected readonly loading = this.projectFacade.loading;
  protected readonly error = this.projectFacade.error;

  file = this.fileManagerService.file; // Variable to store file
  imagePreviewUrl = this.fileManagerService.imagePreviewUrl; // URL for image preview
  fileError = this.fileManagerService.fileError;
  protected onSubmitted = signal<boolean>(false);

  constructor() {
    effect(
      () => {
        if (!this.loading().isLoading && this.onSubmitted()) {
          switch (this.loading().action) {
            case ActionType.UPDATE:
              this.onSubmitted.set(false);
              this.onFormSubmitted.emit('');
              this.fileManagerService.resetFile();
              break;
          }
        }
      },
      { allowSignalWrites: true }
    );
  }

  onSubmit() {
    const file = this.file();
    if (file && !this.fileError()) {
      const formData = new FormData();
      formData.append('fichier', file); // "fichier" est le nom du champ dans PocketBase

      this.projectFacade.update(this.project()?.id!, formData);
      this.onSubmitted.set(true);
    }
  }

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

  get currentImageUrl(): string | null {
    if (this.imagePreviewUrl()) {
      return this.imagePreviewUrl();
    }

    if (this.project()?.fichier) {
      return this.project()!.fichier;
    }

    return 'https://api.dicebear.com/9.x/shapes/svg?seed=nouveau-projet';
  }
}
