"use client";

import { use } from "react";
import { notFound } from "next/navigation";
import Link from "next/link";
import { SafeImage } from "@/components/ui/SafeImage";
import { GroceryTile } from "@/components/silo/GroceryTile";
import { getSiloProduct, siloRecipes } from "@/data/silo-catalog";
import { useCart } from "@/context/cart-context";

type Props = { params: Promise<{ slug: string }> };

export default function RecipeDetailPage({ params }: Props) {
  const { slug } = use(params);
  const recipe = siloRecipes.find((r) => r.slug === slug);
  const { addItem } = useCart();
  if (!recipe) notFound();

  const products = recipe.ingredients
    .map((id) => getSiloProduct(id))
    .filter((p): p is NonNullable<typeof p> => Boolean(p));

  return (
    <div className="mx-auto max-w-[1280px] px-4 py-10 sm:px-6 lg:px-8">
      <Link href="/recipes" className="text-sm font-semibold text-[var(--spruce-ink)]">
        All recipes
      </Link>
      <div className="mt-4 grid gap-8 lg:grid-cols-[1.1fr_0.9fr]">
        <div>
          <p className="text-[11px] font-bold uppercase tracking-[0.18em] text-[var(--straw)]">
            {recipe.time} · serves {recipe.serves}
          </p>
          <h1 className="mt-2 font-serif text-4xl">{recipe.title}</h1>
          <p className="mt-3 text-sm text-muted">{recipe.blurb}</p>
          <button
            type="button"
            onClick={() =>
              products.forEach((p, index) =>
                addItem(p, 1, undefined, {
                  openDrawer: index === products.length - 1,
                }),
              )
            }
            className="btn-bin mt-6"
          >
            Add the board
          </button>
        </div>
        <div className="relative min-h-[240px] overflow-hidden rounded-sm">
          <SafeImage src={recipe.image} alt="" fill className="object-cover" sizes="600px" />
        </div>
      </div>
      <h2 className="mt-10 font-serif text-2xl">From this crib</h2>
      <div className="mt-4 grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4">
        {products.map((p) => (
          <GroceryTile key={p.id} product={p} layout="grid" />
        ))}
      </div>
    </div>
  );
}
