import { redirect } from "next/navigation";
import { setRequestLocale } from "next-intl/server";
import { connectDB } from "@/lib/db";
import { GiftVoucher } from "@/models/GiftVoucher";
import { Client } from "@/models/Client";
import { getSessionClientId } from "@/lib/auth";
import { formatEUR } from "@/lib/orderConstants";
import { AccountPageHeader } from "@/components/account/AccountPageHeader";
import { CopyButton } from "@/components/account/CopyButton";

export const dynamic = "force-dynamic";

export default async function AccountVouchersPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  setRequestLocale(locale);
  const isEn = locale === "en";

  const clientId = await getSessionClientId();
  if (!clientId) redirect(`/${locale}/login?next=%2F${locale}%2Faccount%2Fvouchers`);

  await connectDB();
  const client = await Client.findById(clientId).select("email").lean();
  // Gutscheine sind nicht zwingend an ein Konto gebunden (Kauf ohne Login
  // möglich, siehe requestVoucherAction) — Zuordnung daher über die
  // Käufer-E-Mail oder, falls schon eingelöst, über die Kunden-ID.
  const vouchers = await GiftVoucher.find({
    $or: [{ purchaserEmail: client?.email }, { redeemedByClientId: clientId }],
  })
    .sort({ createdAt: -1 })
    .lean();

  return (
    <div>
      <div className="max-w-2xl">
        <AccountPageHeader
          eyebrow={isEn ? "Vouchers" : "Gutscheine"}
          title={isEn ? "My vouchers" : "Meine Gutscheine"}
        />

        <div className="flex flex-col gap-3">
          {vouchers.map((v) => (
            <div key={String(v._id)} className="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-white/10 bg-[var(--rk-surface)] p-5">
              <div className="min-w-0">
                <div className="flex flex-wrap items-center gap-2">
                  <p className="font-mono text-sm text-[var(--rk-ink)]">
                    {v.code || (isEn ? "Not yet paid" : "Noch nicht bezahlt")}
                  </p>
                  {v.code && (
                    <CopyButton
                      value={v.code}
                      label={isEn ? "Copy" : "Kopieren"}
                      copiedLabel={isEn ? "Copied" : "Kopiert"}
                    />
                  )}
                </div>
                <p className="text-xs text-[var(--rk-ink-muted)] mt-1">
                  {v.recipientName ? `${isEn ? "For" : "Für"} ${v.recipientName} · ` : ""}
                  {v.redeemed
                    ? isEn
                      ? "Redeemed"
                      : "Eingelöst"
                    : v.cancelled
                      ? isEn
                        ? "Cancelled"
                        : "Storniert"
                      : v.paid
                        ? isEn
                          ? "Open"
                          : "Offen"
                        : isEn
                          ? "Awaiting payment"
                          : "Zahlung ausstehend"}
                  {v.expiresAt && !v.redeemed && !v.cancelled
                    ? ` · ${isEn ? "valid until" : "gültig bis"} ${new Date(v.expiresAt).toLocaleDateString(isEn ? "en-GB" : "de-DE")}`
                    : ""}
                </p>
              </div>
              <span className="text-sm shrink-0">{formatEUR(v.amount)}</span>
            </div>
          ))}
          {vouchers.length === 0 && (
            <p className="text-sm text-center text-[var(--rk-ink-muted)]">
              {isEn ? "No vouchers yet." : "Noch keine Gutscheine."}
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
