import { Component, effect, inject, input, signal } from '@angular/core';
import { User } from '@app/domain/users/user.model';
import { ReactiveFormsModule } from '@angular/forms';
import { environment } from '@env/environment';
import { NgTemplateOutlet } from '@angular/common';
import { UserFacade } from '@app/adapters/users/user.facade';
import { ActionType } from '@app/domain/action-type.util';
import { LoadingComponent } from '@app/shared/components/loading/loading.component';
import { UntilDestroy } from '@ngneat/until-destroy';
import { UserViewModel } from '@app/adapters/users/user.presenter.model';
import { FileManagerService } from '@app/adapters/shared/services/file-manager.service';

@Component({
  selector: 'app-user-avatar-form',
  standalone: true,
  imports: [ReactiveFormsModule, NgTemplateOutlet, LoadingComponent],
  templateUrl: './user-avatar-form.component.html',
  styleUrl: './user-avatar-form.component.scss',
})
@UntilDestroy()
export class UserAvatarFormComponent {
  protected readonly environment = environment;
  protected readonly fileManagerService = inject(FileManagerService);
  private readonly facade = inject(UserFacade);
  protected readonly ActionType = ActionType;

  user = input.required<UserViewModel | undefined>();

  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);

  protected readonly loading = this.facade.loading;
  protected readonly error = this.facade.error;

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

  onUserAvatarFormSubmit(): void {
    const file = this.file();
    const user = this.user();

    if (file && !this.fileError() && user?.id) {
      const formData = new FormData();

      formData.append('avatar', file);

      this.facade.update(user.id, formData as unknown as Partial<User>);
      this.onSubmitted.set(true);
    }
  }

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

  get currentAvatarUrl(): string | null {
    const currentUser = this.user();

    if (this.imagePreviewUrl()) {
      return this.imagePreviewUrl();
    }

    if (currentUser?.avatar) {
      return currentUser.avatar;
    }

    return `https://api.dicebear.com/9.x/initials/svg?seed=${currentUser!.name ?? 'trouveTonProfil'}`;
  }
}
