import { Handlers, PageProps } from "$fresh/server.ts";
import { IngredientsList } from "@islands/IngredientsList.tsx";
import { RecipeHero } from "@components/RecipeHero.tsx";
import { MainLayout } from "@components/layouts/main.tsx";
import Counter from "@islands/Counter.tsx";
import { useSignal } from "@preact/signals";
import { getRecipe, Recipe } from "@lib/resource/recipes.ts";
import { RedirectSearchHandler } from "@islands/Search.tsx";
import { KMenu } from "@islands/KMenu.tsx";

export const handler: Handlers<Recipe | null> = {
  async GET(_, ctx) {
    const recipe = await getRecipe(ctx.params.name);
    return ctx.render(recipe);
  },
};

export default function Greet(props: PageProps<Recipe>) {
  const recipe = props.data;

  const portion = recipe.meta?.portion;
  const amount = useSignal(portion || 1);

  const subline = [
    recipe?.meta?.time && `Duration ${recipe.meta.time}`,
  ].filter(Boolean);

  return (
    <MainLayout
      url={props.url}
      title={`Recipes > ${recipe.name}`}
      context={recipe}
    >
      <RedirectSearchHandler />
      <KMenu type="main" context={recipe} />
      <RecipeHero
        data={recipe}
        backlink="/recipes"
        editLink={`https://notes.max-richter.dev/Recipes/${recipe.id}`}
        subline={subline}
      />
      <div class="px-8 text-white mt-10">
        <div class="flex items-center gap-8">
          <h3 class="text-3xl my-5">Ingredients</h3>
          {portion && <Counter count={amount} />}
        </div>
        <IngredientsList
          ingredients={recipe.ingredients}
          amount={amount}
          portion={portion}
        />
        <h3 class="text-3xl my-5">Preparation</h3>
        <pre
          class="whitespace-break-spaces"
          dangerouslySetInnerHTML={{ __html: recipe.preparation || "" }}
        >
          {recipe.preparation}
        </pre>
      </div>
    </MainLayout>
  );
}
