import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { UserStore } from 'src/app/core/interfaces/user.interface';
import { ToastDispatchers } from 'src/app/core/stores/index.dispatchers';
import { Ingredient } from 'src/app/shared/interfaces/services/api-fit/response/ingredient.interface';

import { Recipe } from 'src/app/shared/interfaces/services/api-fit/response/recipe.interface';

import { ApiFitService } from 'src/app/shared/services/api-fit/api-fit.service';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.scss'],
})
export class DetailsComponent {
  isRecipeAuthor = false;

  recipe: Recipe = {
    id: 0,
    name: '',
    creator: '',
    servings: 0,
    pictureUrl: '',
    isLiked: false,
    likes: 0,
    kcal: 0,
    tags: [],
    ingredients: [],
    stepBySteps: [],
  };
  recipeIngredients: Ingredient[] = [];

  isModalNutrientsOpen = false;
  isModalConfirmExclusionOpen = false;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private apiFitService: ApiFitService,
    private titleService: Title,
    private store: Store<{ user: UserStore }>,
    private toastDispatchers: ToastDispatchers,
  ) {}

  async ngOnInit() {
    try {
      const id = await this.setRecipeId();

      this.fetchRecipe(id);
      this.fetchRecipeIngredients(id);

      this.store.subscribe({
        next: (s) => {
          this.isRecipeAuthor = s.user.username === this.recipe.creator;
        },
      });
    } catch (er) {
      this.router.navigate(['/app/foods']);
    }
  }

  setRecipeId() {
    return new Promise(
      (resolve: (id: number) => void, reject: (reason?: unknown) => void) => {
        this.route.params.subscribe({
          next: (p) => {
            const id = parseInt((p['food'] as string).split('-').at(-1) ?? '');

            if (isNaN(id)) {
              reject();
            }

            resolve(id);
          },
          error: reject,
        });
      },
    );
  }

  fetchRecipe(recipeId: Recipe['id']) {
    this.apiFitService.getRecipeById(recipeId).subscribe({
      next: (r) => {
        this.recipe = r.data;

        this.updateUrl();
        this.updateTitle();
      },
      error: () => this.router.navigate(['/app/foods']),
    });
  }

  fetchRecipeIngredients(recipeId: Recipe['id']) {
    this.apiFitService.getRecipeIngredients({ recipeId: recipeId }).subscribe({
      next: (r) => (this.recipeIngredients = r.data),
    });
  }

  toggleLike() {
    let request;

    if (this.recipe.isLiked) {
      request = this.apiFitService.unlikeRecipe({ recipeId: this.recipe.id });
      this.recipe.likes--;
    } else {
      request = this.apiFitService.likeRecipe({ recipeId: this.recipe.id });
      this.recipe.likes++;
    }

    request.subscribe({
      next: () => (this.recipe.isLiked = !this.recipe.isLiked),
    });
  }

  openModalNutrients() {
    this.isModalNutrientsOpen = true;
  }

  updateUrl() {
    const formattedFoodIdentifier =
      this.recipe.name.toLowerCase().replaceAll(' ', '-') +
      '-' +
      this.recipe.id;
    this.router.navigate(['/app/foods', formattedFoodIdentifier]);
  }

  updateTitle() {
    this.titleService.setTitle('FitLife - Receita de ' + this.recipe.name);
  }

  redirectToFilteredRecipes(id: number) {
    this.router.navigate(['/app/foods'], {
      queryParams: { tags_ids: id },
    });
  }

  excludeRecipe() {
    const { id: recipeId } = this.recipe;

    this.apiFitService.excludeRecipe(recipeId).subscribe({
      next: () => {
        this.router.navigate(['/app/foods']);

        this.toastDispatchers.showSuccess({
          message: 'Receita excluída com sucesso',
          delay: 3000,
          isVisible: true,
          shouldHideAutomatically: true,
          showCloseButton: true,
        });
      },
    });
  }

  goToEdit() {
    this.router.navigate(['/app/foods/edit', this.recipe.id]);
  }
}
