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

type IngredientsProps = {
  ingredients: Ingredients;
};

const IngredientList = ({ ingredients }: { ingredients: Ingredient[] }) => {
  return (
    <>
      {ingredients.map((item, index) => {
        // Render Ingredient
        const { type, amount, unit } = item as Ingredient;
        return (
          <tr key={index}>
            <td class="pr-4 py-2">
              {amount + (typeof unit !== "undefined" ? unit : "")}
            </td>
            <td class="px-4 py-2">{type}</td>
          </tr>
        );
      })}
    </>
  );
};

const IngredientTable: FunctionalComponent<{ ingredients: Ingredients }> = (
  { ingredients },
) => {
  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>
                <IngredientList ingredients={groupIngredients} />
              </>
            );
          } else {
            // Render Ingredient
            const { type, amount, unit } = item as Ingredient;
            return (
              <tr key={index}>
                <td class="pr-4 py-2">
                  {(amount ? amount : "") +
                    (unit ? (" " + unit) : "")}
                </td>
                <td class="px-4 py-2">{type}</td>
              </tr>
            );
          }
        })}
      </tbody>
    </table>
  );
};
export const IngredientsList = ({ ingredients }: IngredientsProps) => {
  return <IngredientTable ingredients={ingredients} />;
};
