import { Signal } from "@preact/signals";
import type {
  Ingredient,
  IngredientGroup,
  Ingredients,
} from "../lib/recipes.ts";
import { FunctionalComponent } from "preact";

function numberToString(num: number) {
  return (Math.floor(num * 4) / 4).toString();
}

const Ingredient = (
  { ingredient, amount, key = "", portion = 1 }: {
    ingredient: Ingredient;
    amount: Signal<number>;
    key?: string | number;
    portion?: number;
  },
) => {
  const { type, amount: _amount, unit } = ingredient;

  const finalAmount = (typeof _amount === "number" && amount)
    ? (_amount / portion) * (amount?.value || 1)
    : "";

  return (
    <tr key={key}>
      <td class="pr-4 py-2">
        {numberToString(finalAmount || 0) +
          (typeof unit === "string" ? unit : "")}
      </td>
      <td class="px-4 py-2">{type}</td>
    </tr>
  );
};

export const IngredientsList: FunctionalComponent<
  { ingredients: Ingredients; amount: Signal<number>; portion?: number }
> = (
  { ingredients, amount, portion },
) => {
  return (
    <table class="w-full border-collapse table-auto">
      <tbody>
        {ingredients.map((item, index) => {
          if ("name" in item) {
            // Render IngredientGroup
            const { name, ingredients: groupIngredients } =
              item as IngredientGroup;

            return (
              <>
                <tr key={index}>
                  <td colSpan={3} class="pr-4 py-2 font-italic">{name}</td>
                </tr>
                {groupIngredients.map((item, index) => {
                  // Render Ingredient
                  return (
                    <Ingredient
                      key={index}
                      ingredient={item}
                      amount={amount}
                      portion={portion}
                    />
                  );
                })}
              </>
            );
          } else {
            return (
              <Ingredient ingredient={item} amount={amount} portion={portion} />
            );
          }
        })}
      </tbody>
    </table>
  );
};
