import { notFound } from "next/navigation";
import { headers } from "next/headers";
import QRCode from "qrcode";
import { auth } from "@/lib/auth/server";
import { db, shoppingLists, eq, and } from "@epicure/db";
import { PrintTrigger } from "@/components/recipe/print-trigger";
import { getMessages, formatMessage } from "@/lib/i18n/server";
import { formatQuantity, hasQuantity } from "@/lib/fractions";

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

export default async function ShoppingListPrintPage({ 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 OTHER = m.mealPlan.aisleOther;

  const list = await db.query.shoppingLists.findFirst({
    where: and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session.user.id)),
    with: { items: { orderBy: (t, { asc }) => [asc(t.aisle), asc(t.rawName)] } },
  });

  if (!list) notFound();

  // Only worth printing a scannable link if it actually resolves for whoever
  // scans it — a private list's /s/ link 404s for anyone but the owner.
  const shareUrl = list.isPublic
    ? `${process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000"}/s/${id}`
    : null;
  const qrDataUrl = shareUrl ? await QRCode.toDataURL(shareUrl, { margin: 1, width: 120 }) : null;

  const byAisle = list.items.reduce<Record<string, typeof list.items>>((acc, item) => {
    const key = item.aisle ?? OTHER;
    (acc[key] ??= []).push(item);
    return acc;
  }, {});

  const aisles = Object.keys(byAisle).sort((a, b) =>
    a === OTHER ? 1 : b === OTHER ? -1 : a.localeCompare(b)
  );

  return (
    <>
      <style>{`
        @media print {
          body { margin: 0; }
          .no-print { display: none !important; }
        }
        body {
          font-family: system-ui, sans-serif;
          color: #1a1a1a;
          max-width: 680px;
          margin: 40px auto;
          padding: 0 24px;
          font-size: 14px;
          line-height: 1.6;
        }
        h1 { font-size: 1.8em; margin: 0 0 4px; }
        .subtitle { color: #666; font-size: 0.9em; margin-bottom: 24px; }
        .header-row { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
        .qr-block { text-align: center; flex-shrink: 0; }
        .qr-block img { width: 88px; height: 88px; display: block; }
        .qr-block span { display: block; font-size: 0.65em; color: #999; margin-top: 4px; max-width: 100px; }
        h2 { font-size: 0.9em; text-transform: uppercase; letter-spacing: 0.08em; color: #888; border-bottom: 1px solid #e0e0e0; padding-bottom: 4px; margin: 20px 0 8px; }
        ul { list-style: none; padding: 0; margin: 0; }
        li { display: flex; align-items: baseline; gap: 8px; padding: 5px 0; border-bottom: 1px dotted #eee; font-size: 0.95em; }
        li:last-child { border-bottom: none; }
        .check { width: 16px; height: 16px; border: 1.5px solid #999; border-radius: 3px; flex-shrink: 0; display: inline-block; }
        .checked .check { background: #18181b; border-color: #18181b; }
        .checked span { text-decoration: line-through; color: #999; }
        .qty { color: #666; min-width: 70px; font-variant-numeric: tabular-nums; }
        footer { margin-top: 40px; font-size: 0.75em; color: #aaa; text-align: center; }
        .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;
        }
        .print-btn:hover { background: #3f3f46; }
      `}</style>

      <PrintTrigger />

      <div className="header-row">
        <div>
          <h1>{list.name}</h1>
          <p className="subtitle">
            {formatMessage(m.shoppingLists.itemsChecked, {
              checked: list.items.filter((i) => i.checked).length,
              total: list.items.length,
            })}
            {list.generatedAt ? m.shoppingLists.fromMealPlan : ""}
          </p>
        </div>
        {qrDataUrl && (
          <div className="qr-block">
            {/* eslint-disable-next-line @next/next/no-img-element -- a data: URL, not an optimizable remote image */}
            <img src={qrDataUrl} alt={m.shoppingLists.qrCodeAlt} />
            <span>{m.shoppingLists.qrCodeCaption}</span>
          </div>
        )}
      </div>

      {aisles.map((aisle) => (
        <section key={aisle}>
          {aisles.length > 1 && <h2>{aisle}</h2>}
          <ul>
            {byAisle[aisle]!.map((item) => (
              <li key={item.id} className={item.checked ? "checked" : ""}>
                <span className="check" />
                <span className="qty">
                  {[hasQuantity(item.quantity) ? formatQuantity(parseFloat(item.quantity!)) : null, item.unit].filter(Boolean).join(" ")}
                </span>
                <span>{item.rawName}</span>
              </li>
            ))}
          </ul>
        </section>
      ))}

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