import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';

import { SignupStore } from 'src/app/core/interfaces/store/signup.store';

import { AuthService } from 'src/app/core/services/auth/auth.service';
import { ApiFitService } from 'src/app/shared/services/api-fit/api-fit.service';
import { StoreService } from 'src/app/core/services/store/store.service';
import { LoaderDispatchers, ToastDispatchers } from 'src/app/core/stores/index.dispatchers';
import { Toast } from 'src/app/core/interfaces/store/toast.interface';

@Component({
  selector: 'app-avatar',
  templateUrl: './avatar.component.html',
  styleUrls: ['./avatar.component.scss'],
})
export class AvatarComponent {
  avatar!: File;
  signupModel!: SignupStore;

  constructor(
    private store: Store<{ signup: SignupStore }>,
    private authService: AuthService,
    private apiFitService: ApiFitService,
    private storeService: StoreService,
    private router: Router,
    private loaderDispatcher: LoaderDispatchers,
    private toastDispatchers: ToastDispatchers
  ) {
    this.store.select('signup').subscribe({
      next: (d) => {
        this.signupModel = d;
      },
    });
  }

  ngOnInit() {
    const token = this.authService.getAuthorizationToken();
    (!token || !this.signupModel.fullName) && this.backToSignup();
  }

  backToSignup() {
    this.router.navigate(['app/auth/signup']);
  }

  submitForm() {
    if (!this.avatar) return;
    
    this.loaderDispatcher.showLoader();

    this.apiFitService
      .uploadAvatar({
        image: this.avatar,
      })
      .subscribe({
        next: () => {
          this.setStore();
        },
        error: () => {
          this.toastDispatchers.showError({
            message: 'Ocorreu um erro ao salvar seu avatar. Não se preocupe, você poderá adicioná-lo mais tarde',
            shouldHideAutomatically: true,
            showCloseButton: true,
            delay: 3000
          } as Toast);
          
          this.setStore();
        }
      });
  }

  setStore() {
    this.loaderDispatcher.showLoader();

    this.storeService
    .setStore()
    .then(() => {
      this.router.navigate(['app/home']);
    })
    .finally(() => this.loaderDispatcher.hideLoader());
  }
}
