import {
  Component,
  ElementRef,
  Input,
  OnChanges,
  SimpleChanges,
  ViewChild,
} from '@angular/core';
import { Router } from '@angular/router';
import {
  Meal,
  MealTime,
} from 'src/app/shared/interfaces/services/api-fit/response/meal.interface';
import { IconName } from '../../icon/icon.component';

@Component({
  selector: 'app-meal-card',
  templateUrl: './meal-card.component.html',
  styleUrls: ['./meal-card.component.scss'],
})
export class MealCardComponent implements OnChanges {
  @Input() meal: Meal = {
    id: 0,
    mealTime: '',
    mealDate: new Date(),
    foods: [],
    recipes: [],
    nutrients: [],
  };

  @ViewChild('informationContainer')
  informationContainer!: ElementRef<HTMLDivElement>;

  calories = 0;

  isOpen = false;
  containerHeight = 0;

  mealIcons: Record<MealTime['name'], IconName> = {
    'Café da Manhã': 'breakfast',
    Almoço: 'lunch',
    Jantar: 'dinner',
    Snacks: 'snacks',
  };

  constructor(private router: Router) {}

  ngOnInit() {
    this.sumTotalCalories();
    this.getInformationContainerHeight();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['meal']?.currentValue) {
      this.isOpen = false;
      this.sumTotalCalories();
    }
  }

  sumTotalCalories() {
    this.calories = this.meal.foods.reduce((acc, food) => {
      const kcal = isNaN(food.kcal) ? 0 : food.kcal;
      return acc + kcal;
    }, 0);

    this.calories += this.meal.recipes.reduce((acc, recipe) => {
      const kcal = isNaN(recipe.consumedKcal) ? 0 : recipe.consumedKcal;
      return acc + kcal;
    }, 0);
  }

  getInformationContainerHeight() {
    if (!this.informationContainer?.nativeElement) return;

    this.containerHeight = this.informationContainer.nativeElement.scrollHeight;
  }

  toggleOpen() {
    this.isOpen = !this.isOpen;

    if (this.isOpen) {
      this.getInformationContainerHeight();
    }
  }

  goToEdit() {
    this.router.navigate(['/app/meals/', this.meal.id]);
  }

  goToCreate() {
    const mealTime = this.meal.mealTime.replaceAll(/ /g, '-').toLowerCase();
    const date = this.meal.mealDate.toISOString().split('T')[0];

    this.router.navigate(['/app/meals/create', mealTime], {
      queryParams: {
        date,
      },
    });
  }
}
