import type { Metadata } from "next";
import { redirect, notFound } from "next/navigation";
import { Reveal } from "../../components/Reveal";
import { getSessionCustomer, getWishlist } from "../../lib/customerAuth";
import { getProductsByIds, getWishlistEnabled, getDefaultTaxRatePercent, getKleinunternehmer } from "../../lib/payload";
import { KontoShell } from "../components/KontoShell";
import { AccountIdentity } from "../components/AccountIdentity";
import { MerklisteGrid } from "./components/MerklisteGrid";

// robots: noindex — account area, same reasoning as /konto/bestellungen.
export const metadata: Metadata = {
  title: "Meine Merkliste",
  description: "Deine gemerkten Produkte bei einfach produktiv.",
  robots: {
    index: false,
    follow: true,
  },
};

export default async function KontoMerklistePage() {
  const session = await getSessionCustomer();
  // ?redirect= back to this page — landing on the generic account/orders
  // overview after logging in from the wishlist icon (the common entry
  // point, unlike most other /konto/* pages that are only ever reached
  // once already logged in) would silently lose the wishlist context the
  // customer actually came here for.
  if (!session) redirect("/konto/login?redirect=%2Fkonto%2Fmerkliste");

  // The feature can be switched off after a customer already had rows in
  // their wishlist — 404 rather than showing a stale page for a feature
  // that's no longer offered, same reasoning as any other feature-flagged
  // route in this codebase.
  const wishlistEnabled = await getWishlistEnabled();
  if (!wishlistEnabled) notFound();

  const [wishlistItems, defaultTaxRate, kleinunternehmer] = await Promise.all([
    getWishlist(session.token, session.customer.id),
    getDefaultTaxRatePercent(),
    getKleinunternehmer(),
  ]);
  const initialProducts = await getProductsByIds(wishlistItems.map((i) => i.productId));

  return (
    <KontoShell>
      <Reveal className="flex flex-col gap-6 items-start w-full">
        <div className="flex flex-col gap-1 items-start">
          <p className="font-semibold text-h-feature text-text-primary" style={{ fontFamily: "var(--font-lora)" }}>
            Meine Merkliste
          </p>
          <AccountIdentity email={session.customer.email} customerNumber={session.customer.customerNumber} />
        </div>

        <MerklisteGrid initialProducts={initialProducts} defaultTaxRate={defaultTaxRate} kleinunternehmer={kleinunternehmer} />
      </Reveal>
    </KontoShell>
  );
}
