"use client"; import { useState } from "react"; import { toast } from "sonner"; import { Trash2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; type Day = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun"; type MealType = "breakfast" | "lunch" | "dinner" | "snack"; const DAYS: Day[] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]; const MEAL_TYPES: MealType[] = ["breakfast", "lunch", "dinner", "snack"]; type Entry = { id: string; day: Day; mealType: MealType; servings: number; recipe: { id: string; title: string } | null; }; type UserRecipe = { id: string; title: string }; export function SharedMealPlanView({ mealPlanId, initialEntries, userRecipes, canEdit, }: { mealPlanId: string; initialEntries: Entry[]; userRecipes: UserRecipe[]; canEdit: boolean; }) { const [entries, setEntries] = useState(initialEntries); const [addingCell, setAddingCell] = useState(null); function cellKey(day: Day, mealType: MealType) { return `${day}-${mealType}`; } async function addEntry(day: Day, mealType: MealType, recipeId: string) { const res = await fetch(`/api/v1/meal-plans/shared/${mealPlanId}/entries`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ day, mealType, recipeId, servings: 2 }), }); if (!res.ok) { toast.error("Could not add recipe"); return; } const { id } = await res.json() as { id: string }; const recipe = userRecipes.find((r) => r.id === recipeId) ?? null; setEntries((prev) => [ ...prev.filter((e) => !(e.day === day && e.mealType === mealType)), { id, day, mealType, servings: 2, recipe }, ]); setAddingCell(null); } async function removeEntry(entry: Entry) { const res = await fetch(`/api/v1/meal-plans/shared/${mealPlanId}/entries?entryId=${entry.id}`, { method: "DELETE", }); if (!res.ok) { toast.error("Could not remove entry"); return; } setEntries((prev) => prev.filter((e) => e.id !== entry.id)); } return (
{DAYS.map((day) => ( ))} {MEAL_TYPES.map((mealType) => ( {DAYS.map((day) => { const entry = entries.find((e) => e.day === day && e.mealType === mealType); const key = cellKey(day, mealType); return ( ); })} ))}
{day}
{mealType} {entry ? (
{entry.recipe?.title ?? "—"} {canEdit && ( )}
) : canEdit ? ( addingCell === key ? ( ) : ( ) ) : ( )}
); }