import type { Metadata } from "next";
import Image from "next/image";
import Script from "next/script";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
import { Clock, Users, ChefHat, Globe } from "lucide-react";
import { auth } from "@/lib/auth/server";
import { db, recipes, eq } from "@epicure/db";
import { isFollowing } from "@/lib/social-follows";
import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ServingScaler } from "@/components/recipe/serving-scaler";
import { getPublicUrl } from "@/lib/storage";
import { hasQuantity } from "@/lib/fractions";
import { cn } from "@/lib/utils";
import { getMessages, formatMessage } from "@/lib/i18n/server";

type Params = { params: Promise<{ id: string }> };

export async function generateMetadata({ params }: Params): Promise<Metadata> {
  const { id } = await params;
  const recipe = await db.query.recipes.findFirst({
    where: (r, { and, eq }) => and(eq(r.id, id), eq(r.visibility, "public")),
  });
  if (!recipe) return {};
  return {
    title: recipe.title,
    description: recipe.description ?? undefined,
    openGraph: {
      title: recipe.title,
      description: recipe.description ?? undefined,
      type: "article",
    },
  };
}

export default async function PublicRecipePage({ params }: Params) {
  const { id } = await params;
  const session = await auth.api.getSession({ headers: await headers() }).catch(() => null);

  const m = getMessages((session?.user as { locale?: string } | undefined)?.locale);
  const unitPref = (session?.user as { unitPref?: string } | undefined)?.unitPref === "imperial" ? "imperial" : "metric";

  const recipe = await db.query.recipes.findFirst({
    where: (r, { and, eq, ne }) => and(eq(r.id, id), ne(r.visibility, "private")),
    with: {
      author: true,
      ingredients: { orderBy: (t, { asc }) => asc(t.order) },
      steps: { orderBy: (t, { asc }) => asc(t.order) },
      photos: { orderBy: (t, { asc }) => asc(t.order) },
    },
  });

  if (!recipe) notFound();

  // "Followers only" recipes are excluded from the anonymous-accessible query
  // above only by being neither public nor unlisted — but ne("private") still
  // lets them through. This route has no session-based access control at all
  // otherwise, so gate them explicitly: the author, or a signed-in follower.
  if (recipe.visibility === "followers") {
    const viewerId = session?.user?.id;
    const allowed = !!viewerId && (viewerId === recipe.authorId || await isFollowing(viewerId, recipe.authorId));
    if (!allowed) notFound();
  }

  const cover = recipe.photos.find((p) => p.isCover) ?? recipe.photos[0];
  const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
  const activeTags = Object.entries(recipe.dietaryTags ?? {})
    .filter(([, v]) => v)
    .map(([k]) => m.recipe.dietary[k as keyof typeof m.recipe.dietary])
    .filter(Boolean);

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Recipe",
    name: recipe.title,
    description: recipe.description,
    author: { "@type": "Person", name: recipe.author.name },
    recipeYield: String(recipe.baseServings),
    prepTime: recipe.prepMins ? `PT${recipe.prepMins}M` : undefined,
    cookTime: recipe.cookMins ? `PT${recipe.cookMins}M` : undefined,
    recipeIngredient: recipe.ingredients.map((i) =>
      [hasQuantity(i.quantity) ? i.quantity : null, i.unit, i.rawName].filter(Boolean).join(" ")
    ),
    recipeInstructions: recipe.steps.map((s) => ({
      "@type": "HowToStep",
      text: s.instruction,
    })),
    image: cover ? [getPublicUrl(cover.storageKey)] : undefined,
  };

  return (
    <>
      <Script id="recipe-jsonld" type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }} />
      <div className="container mx-auto max-w-3xl px-4 py-8 space-y-8">
        {/* Breadcrumb-style nav */}
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Globe className="h-3.5 w-3.5" />
          <span>{m.publicRecipe.publicRecipeBy}</span>
          <Link href={`/u/${recipe.author.username ?? recipe.author.id}`} className="hover:text-foreground font-medium">
            {recipe.author.name}
          </Link>
          {session && (
            <div className="ml-auto">
              <Link href={`/recipes/${id}`} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
                {m.publicRecipe.viewInLibrary}
              </Link>
            </div>
          )}
          {!session && (
            <div className="ml-auto flex items-center gap-2">
              <Link href="/signup" className={cn(buttonVariants({ size: "sm" }))}>{m.publicRecipe.signUpFree}</Link>
              <Link href="/login" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>{m.publicRecipe.logIn}</Link>
            </div>
          )}
        </div>

        <div className="space-y-4">
          <h1 className="text-3xl font-bold tracking-tight">{recipe.title}</h1>
          {recipe.description && (
            <p className="text-muted-foreground leading-relaxed">{recipe.description}</p>
          )}
          <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
            {recipe.difficulty && <Badge>{recipe.difficulty}</Badge>}
            <span className="flex items-center gap-1"><Users className="h-4 w-4" />{formatMessage(m.recipe.servings, { count: recipe.baseServings })}</span>
            {recipe.prepMins && <span className="flex items-center gap-1"><Clock className="h-4 w-4" />{formatMessage(m.recipe.prep, { mins: recipe.prepMins })}</span>}
            {recipe.cookMins && <span className="flex items-center gap-1"><ChefHat className="h-4 w-4" />{formatMessage(m.recipe.cook, { mins: recipe.cookMins })}</span>}
            {totalMins > 0 && recipe.prepMins && recipe.cookMins && <span>({formatMessage(m.recipe.total, { mins: totalMins })})</span>}
          </div>
          {activeTags.length > 0 && (
            <div className="flex flex-wrap gap-1.5">
              {activeTags.map((tag) => <Badge key={tag} variant="secondary" className="text-xs">{tag}</Badge>)}
            </div>
          )}
        </div>

        {cover && (
          <div className="relative aspect-video overflow-hidden rounded-xl bg-muted">
            <Image src={getPublicUrl(cover.storageKey)} alt={recipe.title} fill unoptimized className="object-cover" />
          </div>
        )}

        <Separator />

        {recipe.ingredients.length > 0 && (
          <div className="space-y-4">
            <h2 className="text-xl font-semibold">{m.recipe.ingredients}</h2>
            <ServingScaler
              baseServings={recipe.baseServings}
              unitPref={unitPref}
              ingredients={recipe.ingredients.map((ing) => ({
                id: ing.id, rawName: ing.rawName, quantity: ing.quantity, unit: ing.unit, note: ing.note, order: ing.order,
              }))}
            />
          </div>
        )}

        {recipe.steps.length > 0 && (
          <>
            <Separator />
            <div className="space-y-6">
              <h2 className="text-xl font-semibold">{m.recipe.instructions}</h2>
              <ol className="space-y-6">
                {recipe.steps.map((step, i) => (
                  <li key={step.id} className="flex gap-4">
                    <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-bold">{i + 1}</div>
                    <p className="flex-1 pt-1 leading-relaxed">{step.instruction}</p>
                  </li>
                ))}
              </ol>
            </div>
          </>
        )}

        {!session && (
          <div className="rounded-xl border bg-muted/40 p-6 text-center space-y-3">
            <p className="font-semibold">{m.publicRecipe.wantToSave}</p>
            <p className="text-sm text-muted-foreground">{m.publicRecipe.wantToSaveDescription}</p>
            <Link href="/signup" className={cn(buttonVariants())}>{m.publicRecipe.getStartedFree}</Link>
          </div>
        )}
      </div>
    </>
  );
}
