import { Context, PageProps } from "fresh";
import { MainLayout } from "@components/layouts/main.tsx";
import { Grid } from "@components/Grid.tsx";
import { TbArrowLeft } from "@preact-icons/tb";
import { KMenu } from "@islands/KMenu.tsx";
import { RedirectSearchHandler } from "@islands/Search.tsx";
import { ResourceCard } from "@components/Card.tsx";
import { listResources } from "@lib/marka/index.ts";
import { parseResourceUrl, searchResource } from "@lib/search.ts";
import { GenericResource, RecipeResource } from "@lib/marka/schema.ts";

export const handler = {
  async GET(ctx: Context<{ test: number }>) {
    const req = ctx.req;
    const recipes = await listResources<RecipeResource>("recipes");
    const searchParams = parseResourceUrl(req.url);
    const searchResults = searchParams &&
      await searchResource({ ...searchParams, types: ["recipes"] });
    return { data: { recipes, searchResults } };
  },
};

export default function Page(
  { data, url }: PageProps<{
    recipes: RecipeResource[] | null;
    searchResults: GenericResource[];
  }>,
) {
  const { recipes, searchResults } = data;
  return (
    <MainLayout
      url={url}
      title="Recipes"
      searchResults={searchResults}
      context={{ type: "recipes" }}
    >
      <RedirectSearchHandler />
      <KMenu type="main" context={{ type: "recipes" }} />
      <header class="flex gap-4 items-center mb-2 lg:mb-5 md:hidden">
        <a
          class="px-4 lg:ml-4 py-2 bg-gray-300 text-gray-800 rounded-lg flex items-center gap-1"
          href="/"
        >
          <TbArrowLeft class="w-5 h-5" />
          Back
        </a>

        <h3 class="text-2xl text-white font-light">🍽️ Recipes</h3>
      </header>
      <Grid>
        {recipes?.filter((s) => !!s?.content?.name).map((doc) => {
          return <ResourceCard sublink="recipes" key={doc.name} res={doc} />;
        })}
      </Grid>
    </MainLayout>
  );
}
