import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  Output,
  SimpleChanges,
} from '@angular/core';

import {
  FoodCardProps,
  FoodCardType,
} from 'src/app/shared/interfaces/components/cards/food-card/food-card.interface';

@Component({
  selector: 'app-food-card',
  templateUrl: './food-card.component.html',
  styleUrls: ['./food-card.component.scss'],
})
export class FoodCardComponent implements OnChanges {
  @Input() food: FoodCardProps = {
    id: 0,
    name: '',
    kcal: 0,
    quantity: 0,
    type: 'food',
  };
  @Input() type: FoodCardType = 'view';
  @Input() isSelected = false;

  @Input() canEditFood = false;
  @Input() showButtons = true;
  @Input() showEditOption = true;
  @Input() showDeleteOption = true;
  @Output() onSelect = new EventEmitter<boolean>();

  @Output() onRemove = new EventEmitter<FoodCardProps>();
  @Output() onEdit = new EventEmitter<FoodCardProps>();
  @Output() foodChange = new EventEmitter<FoodCardProps>();

  units = {
    food: {
      singular: 'g',
      plural: 'g'
    },
    recipe: {
      singular: ' porção',
      plural: ' porções'
    },
  };

  kcalPerPortion = 0;

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['food']) {
      this.calculatekcalPerPortion();
    }
  }

  getCalories() {
    return isNaN(this.food.kcal) ? 0 : Math.round(this.food.kcal);
  }

  calculatekcalPerPortion() {
    if (this.food.type === 'food') {
      this.kcalPerPortion = this.food.kcal / this.food.quantity;
    }

    if (this.food.type === 'recipe') {
      if (this.food.quantity === 0) {
        this.kcalPerPortion = 0;
        return;
      }

      this.kcalPerPortion = this.food.kcal / this.food.quantity;
    }

    if (isNaN(this.kcalPerPortion)) {
      this.kcalPerPortion = 0;
    }
  }

  handleEditClick() {
    this.onEdit.emit(this.food);
  }

  handleDeleteClick() {
    this.onRemove.emit(this.food);
  }

  handleQuantityChange(quantity: number) {
    this.food.kcal = Math.round(this.kcalPerPortion * quantity);
    this.food.quantity = quantity;

    this.foodChange.emit(this.food);
  }

  handleSelectClick() {
    if (this.isSelected) return;

    this.isSelected = true;
    this.onSelect.emit(this.isSelected);
  }
}
