import { Component, effect, inject, Input, output, signal } from '@angular/core';
import { User } from '@app/domain/users/user.model';
import { ReactiveFormsModule } from '@angular/forms';
import { environment } from '@env/environment';
import { NgClass, NgTemplateOutlet } from '@angular/common';
import { ToastrService } from 'ngx-toastr';
import { UserFacade } from '@app/ui/users/user.facade';
import { ActionType } from '@app/domain/action-type.util';
import { LoadingComponent } from '@app/shared/components/loading/loading.component';

@Component({
  selector: 'app-user-avatar-form',
  standalone: true,
  imports: [ReactiveFormsModule, NgClass, NgTemplateOutlet, LoadingComponent],
  templateUrl: './user-avatar-form.component.html',
  styleUrl: './user-avatar-form.component.scss',
})
export class UserAvatarFormComponent {
  private readonly toastrService = inject(ToastrService);
  protected readonly environment = environment;
  private readonly facade = inject(UserFacade);
  @Input({ required: true }) user: User | undefined = undefined;

  onFormSubmitted = output<any>();

  file: File | null = null; // Variable to store file
  imagePreviewUrl: string | null = null; // URL for image preview
  protected onSubmitted = signal<boolean>(false);

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

  constructor() {
    let message = '';

    effect(() => {
      if (!this.loading().isLoading && this.onSubmitted()) {
        switch (this.loading().action) {
          case ActionType.UPDATE:
            message = `Votre photo de profile a bien été modifier !`;
            this.customToast(ActionType.UPDATE, message);
            this.onSubmitted.set(false);
            break;
        }
      }
    });
  }

  onUserAvatarFormSubmit() {
    if (this.file != null) {
      const formData = new FormData();
      formData.append('avatar', this.file); // "avatar" est le nom du champ dans PocketBase

      this.facade.update(this.user?.id!, formData as Partial<User>);

      this.onFormSubmitted.emit('');
      this.onSubmitted.set(true);
    }
  }

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

  private readFile(file: File) {
    const reader = new FileReader();
    reader.onload = (e) => {
      this.imagePreviewUrl = e.target?.result as string;
    };
    reader.readAsDataURL(file);
  }

  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.UPDATE ? 'Mise à jour' : ''}`,
      {
        closeButton: true,
        progressAnimation: 'decreasing',
        progressBar: true,
      }
    );
  }

  protected readonly ActionType = ActionType;
}
