import { notFound } from "next/navigation";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes, eq, and } from "@epicure/db";
import { PrintTrigger } from "@/components/recipe/print-trigger";
import { hasQuantity } from "@/lib/fractions";

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 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) },
    },
  });

  if (!recipe) notFound();

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

  const DIETARY_LABELS: Record<string, string> = {
    vegan: "Vegan",
    vegetarian: "Vegetarian",
    glutenFree: "Gluten-free",
    dairyFree: "Dairy-free",
    nutFree: "Nut-free",
    halal: "Halal",
    kosher: "Kosher",
  };

  const activeTags = Object.entries(recipe.dietaryTags ?? {})
    .filter(([, v]) => v)
    .map(([k]) => DIETARY_LABELS[k])
    .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; }
        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; }
        .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>
        <h1>{recipe.title}</h1>

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

        <div className="meta">
          {recipe.baseServings && <span>Serves {recipe.baseServings}</span>}
          {recipe.prepMins && <span>Prep {recipe.prepMins} min</span>}
          {recipe.cookMins && <span>Cook {recipe.cookMins} min</span>}
          {totalMins > 0 && <span>Total {totalMins} min</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>Ingredients</h2>
            <ul className="ingredients">
              {recipe.ingredients.map((ing) => (
                <li key={ing.id}>
                  <span className="qty">
                    {[hasQuantity(ing.quantity) ? ing.quantity : null, ing.unit].filter(Boolean).join(" ")}
                  </span>
                  {ing.rawName}
                  {ing.note && <span style={{ color: "#888" }}> ({ing.note})</span>}
                </li>
              ))}
            </ul>
          </>
        )}

        {recipe.steps.length > 0 && (
          <>
            <h2>Instructions</h2>
            <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>
          </>
        )}
      </article>

      <footer>Printed from Epicure</footer>
    </>
  );
}
