import { notFound } from "next/navigation";
import { headers } from "next/headers";
import QRCode from "qrcode";
import { auth } from "@/lib/auth/server";
import { db, recipes, eq, and } from "@epicure/db";
import { PrintTrigger } from "@/components/recipe/print-trigger";
import { formatIngredientQuantity } from "@/lib/unit-conversion";
import { getMessages, formatMessage } from "@/lib/i18n/server";

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

export default async function RecipePrintPage({ params }: Params) {
  const { id } = await params;
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return null;

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

  const recipe = await db.query.recipes.findFirst({
    where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)),
    with: {
      ingredients: { orderBy: (t, { asc }) => asc(t.order) },
      steps: { orderBy: (t, { asc }) => asc(t.order) },
      batchDishes: { orderBy: (t, { asc }) => asc(t.order) },
    },
  });

  if (!recipe) notFound();

  // /r/[id] resolves anonymously for "public" and "unlisted" only (see
  // app/r/[id]/page.tsx) — "private" and "followers" have no link a random
  // scanner of this QR code could actually open.
  const shareUrl = recipe.visibility === "public" || recipe.visibility === "unlisted"
    ? `${process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000"}/r/${id}`
    : null;
  const qrDataUrl = shareUrl ? await QRCode.toDataURL(shareUrl, { margin: 1, width: 120 }) : null;

  const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);

  const stepGroups: Array<{ label: string; steps: typeof recipe.steps }> = [];
  if (recipe.isBatchCook) {
    for (const step of recipe.steps) {
      const label = step.appliesTo.length === 0 ? m.recipe.batchCookPrep : step.appliesTo.join(" + ");
      const last = stepGroups[stepGroups.length - 1];
      if (last && last.label === label) last.steps.push(step);
      else stepGroups.push({ label, steps: [step] });
    }
  }

  const activeTags = Object.entries(recipe.dietaryTags ?? {})
    .filter(([, v]) => v)
    .map(([k]) => m.recipe.dietary[k as keyof typeof m.recipe.dietary])
    .filter(Boolean);

  return (
    <>
      <style>{`
        @media print {
          body { margin: 0; }
          .no-print { display: none !important; }
        }
        body {
          font-family: Georgia, 'Times New Roman', serif;
          color: #1a1a1a;
          max-width: 680px;
          margin: 40px auto;
          padding: 0 24px;
          font-size: 14px;
          line-height: 1.6;
        }
        h1 { font-size: 2em; margin: 0 0 8px; line-height: 1.2; }
        .title-row { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
        .qr-block { text-align: center; flex-shrink: 0; font-family: system-ui, sans-serif; }
        .qr-block img { width: 84px; height: 84px; display: block; }
        .qr-block span { display: block; font-size: 0.65em; color: #999; margin-top: 4px; max-width: 100px; }
        h2 { font-size: 1.1em; text-transform: uppercase; letter-spacing: 0.08em; border-bottom: 1px solid #ccc; padding-bottom: 4px; margin: 24px 0 12px; }
        .meta { display: flex; gap: 24px; font-size: 0.85em; color: #555; margin: 12px 0 16px; flex-wrap: wrap; }
        .meta span { display: flex; align-items: center; gap: 4px; }
        .tags { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 16px; }
        .tag { border: 1px solid #ccc; border-radius: 4px; padding: 1px 8px; font-size: 0.8em; font-family: system-ui, sans-serif; }
        .description { color: #444; font-style: italic; margin-bottom: 16px; }
        ul.ingredients { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 4px 24px; }
        ul.ingredients li { padding: 4px 0; border-bottom: 1px dotted #e0e0e0; font-family: system-ui, sans-serif; font-size: 0.9em; }
        ul.ingredients li .qty { color: #666; min-width: 60px; display: inline-block; }
        ol.steps { padding-left: 20px; margin: 0; }
        ol.steps li { padding: 6px 0 6px 4px; border-bottom: 1px dotted #e0e0e0; font-size: 0.95em; }
        ol.steps li:last-child { border-bottom: none; }
        h3.section { font-size: 0.85em; text-transform: uppercase; letter-spacing: 0.06em; color: #777; margin: 18px 0 6px; font-family: system-ui, sans-serif; }
        .dish { border: 1px solid #ddd; border-radius: 6px; padding: 10px 14px; margin: 10px 0; font-family: system-ui, sans-serif; }
        .dish-name { font-weight: 600; margin: 0 0 4px; }
        .dish-storage { font-size: 0.85em; color: #666; margin: 0 0 6px; }
        .dish-dayof { font-size: 0.9em; margin: 0; }
        .timer { font-size: 0.85em; color: #666; font-family: system-ui, sans-serif; margin-left: 8px; }
        footer { margin-top: 40px; font-size: 0.75em; color: #aaa; text-align: center; font-family: system-ui, sans-serif; }
        .print-btn {
          position: fixed; top: 16px; right: 16px; padding: 8px 16px;
          background: #18181b; color: white; border: none; border-radius: 6px;
          cursor: pointer; font-size: 13px; font-family: system-ui, sans-serif;
        }
        .print-btn:hover { background: #3f3f46; }
      `}</style>

      <PrintTrigger />

      <article>
        <div className="title-row">
          <h1>{recipe.title}</h1>
          {qrDataUrl && (
            <div className="qr-block">
              {/* eslint-disable-next-line @next/next/no-img-element -- a data: URL generated server-side, not an optimizable remote image */}
              <img src={qrDataUrl} alt={m.recipe.qrCodeAlt} />
              <span>{m.recipe.qrCodeCaption}</span>
            </div>
          )}
        </div>

        {recipe.description && (
          <p className="description">{recipe.description}</p>
        )}

        <div className="meta">
          {recipe.baseServings && <span>{formatMessage(m.recipe.servings, { count: recipe.baseServings })}</span>}
          {recipe.prepMins && <span>{formatMessage(m.recipe.prep, { mins: recipe.prepMins })}</span>}
          {recipe.cookMins && <span>{formatMessage(m.recipe.cook, { mins: recipe.cookMins })}</span>}
          {totalMins > 0 && <span>{formatMessage(m.recipe.total, { mins: totalMins })}</span>}
          {recipe.difficulty && <span>{recipe.difficulty.charAt(0).toUpperCase() + recipe.difficulty.slice(1)}</span>}
        </div>

        {activeTags.length > 0 && (
          <div className="tags">
            {activeTags.map((tag) => (
              <span key={tag} className="tag">{tag}</span>
            ))}
          </div>
        )}

        {recipe.ingredients.length > 0 && (
          <>
            <h2>{m.recipe.ingredients}</h2>
            <ul className="ingredients">
              {recipe.ingredients.map((ing) => (
                <li key={ing.id}>
                  <span className="qty">
                    {formatIngredientQuantity(ing.quantity, ing.unit, unitPref)}
                  </span>
                  {ing.rawName}
                  {ing.note && <span style={{ color: "#888" }}> ({ing.note})</span>}
                </li>
              ))}
            </ul>
          </>
        )}

        {recipe.steps.length > 0 && (
          <>
            <h2>{m.recipe.instructions}</h2>
            {recipe.isBatchCook ? (
              stepGroups.map((group, gi) => (
                <div key={gi}>
                  <h3 className="section">{group.label}</h3>
                  <ol className="steps">
                    {group.steps.map((step) => (
                      <li key={step.id}>{step.instruction}</li>
                    ))}
                  </ol>
                </div>
              ))
            ) : (
              <ol className="steps">
                {recipe.steps.map((step) => (
                  <li key={step.id}>
                    {step.instruction}
                    {!!step.timerSeconds && (
                      <span className="timer">⏱ {Math.floor(step.timerSeconds / 60)} min</span>
                    )}
                  </li>
                ))}
              </ol>
            )}
          </>
        )}

        {recipe.isBatchCook && recipe.batchDishes.length > 0 && (
          <>
            <h2>{m.recipe.batchCookDishesTitle}</h2>
            {recipe.batchDishes.map((dish) => (
              <div key={dish.id} className="dish">
                <p className="dish-name">{dish.name}</p>
                <p className="dish-storage">
                  {formatMessage(m.recipe.batchCookFridgeDays, { days: dish.fridgeDays })}
                  {dish.freezerFriendly && ` · ${m.recipe.batchCookFreezerFriendly}`}
                  {dish.freezerNote && ` — ${dish.freezerNote}`}
                </p>
                <p className="dish-dayof"><strong>{m.recipe.batchCookDayOf}:</strong> {dish.dayOfInstructions}</p>
              </div>
            ))}
          </>
        )}
      </article>

      <footer>{m.print.footer}</footer>
    </>
  );
}
