import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Ingredient } from 'src/app/shared/interfaces/services/api-fit/response/ingredient.interface';
import { NutritionalInformation } from '../../nutrition-table/nutrition-table.component';
import {
  primaryColor,
  quaternaryColor,
  secondaryColor,
} from '../../progress/progress.component';

@Component({
  selector: 'app-nutritional-informations',
  templateUrl: './nutritional-informations.component.html',
  styleUrls: ['./nutritional-informations.component.scss'],
})
export class NutritionalInformationsComponent {
  @Input() isVisible = false;
  @Input() ingredients: Ingredient[] = [];
  @Input() servings = 1;
  @Input() onlyMacros = true;

  @Output() isVisibleChange = new EventEmitter<boolean>();

  nutritionalInformations: NutritionalInformation[] = [];

  macros = ['carboidrato', 'proteína', 'lipídeos'];
  charts: {
    name: string;
    primaryColor: primaryColor;
    secondaryColor: secondaryColor;
    subtitleColor: quaternaryColor;
    value: string;
  }[] = [
    {
      name: 'Carboidratos',
      primaryColor: 'var(--yellow-100)',
      secondaryColor: 'var(--yellow-050)',
      subtitleColor: 'var(--yellow-300)',
      value: '0%',
    },
    {
      name: 'Proteína',
      primaryColor: 'var(--blue-100)',
      secondaryColor: 'var(--blue-050)',
      subtitleColor: 'var(--blue-300)',
      value: '0%',
    },
    {
      name: 'Lipídeos',
      primaryColor: 'var(--red-100)',
      secondaryColor: 'var(--red-050)',
      subtitleColor: 'var(--red-300)',
      value: '0%',
    },
    {
      name: 'Fibras',
      primaryColor: 'var(--purple-100)',
      secondaryColor: 'var(--purple-050)',
      subtitleColor: 'var(--purple-300)',
      value: '0%',
    },
  ];

  setCharts(nutritionalInformations: NutritionalInformation[]) {
    nutritionalInformations.forEach((n) => {
      const nutrientName = n.name.split(' ')[0];

      const chart = this.charts.find((c) =>
        c.name.toLowerCase().startsWith(nutrientName.toLowerCase()),
      );
      if (!chart) return;

      const vd = n.vd === '*' ? 0 : parseInt(n.vd.replace('%', ''), 10);
      chart.value = vd === 0 ? '0' : `${vd}%`;
    });
  }

  getPercentage(vd: string) {
    const percentage = vd.replace('%', '');
    return parseInt(percentage || '', 10);
  }

  handleClose() {
    this.isVisibleChange.emit(false);
  }
}
