import { getTranslations, setRequestLocale } from "next-intl/server";
import { redirect } from "next/navigation";
import { connectDB } from "@/lib/db";
import { Order } from "@/models/Order";
import { Contract } from "@/models/Contract";
import { getSessionClientId } from "@/lib/auth";
import { AccountPageHeader } from "@/components/account/AccountPageHeader";
import { AccountOrdersList, type OrderRow } from "@/components/account/AccountOrdersList";
import { ORDER_TAG_COLORS, formatDatePeriod, type OrderTag } from "@/lib/orderConstants";

export const dynamic = "force-dynamic";

export default async function AccountOrdersPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  setRequestLocale(locale);
  const to = await getTranslations({ locale, namespace: "orders" });
  const isEn = locale === "en";

  const clientId = await getSessionClientId();
  if (!clientId) redirect(`/${locale}/login`);

  await connectDB();
  const orders = await Order.find({ clientId }).sort({ createdAt: -1 }).lean();
  const unsignedOrderIds = new Set(
    (await Contract.find({ orderId: { $in: orders.map((o) => o._id) }, status: "sent" }).select("orderId").lean()).map((c) =>
      String(c.orderId)
    )
  );

  const rows: OrderRow[] = orders.map((o) => ({
    id: String(o._id),
    title: o.characterOrConcept,
    tagLabel: to(`orderTags.${o.tag}`),
    tagColor: ORDER_TAG_COLORS[o.tag as OrderTag] || "#a3a1a6",
    meta: [
      to(`shootingTypes.${o.shootingType}`),
      o.eventLocation || "",
      o.datePeriod ? formatDatePeriod(o.datePeriod, isEn ? "en" : "de") : "",
    ]
      .filter(Boolean)
      .join(" · "),
    phase: String(o.tag).startsWith("done_") ? "done" : "active",
    unsignedContractLabel: unsignedOrderIds.has(String(o._id)) ? to("contractAwaitingSignature") : null,
  }));

  return (
    <div>
      <div className="max-w-2xl">
        <AccountPageHeader eyebrow={to("allOrdersEyebrow")} title={to("allOrdersTitle")} />
        {rows.length === 0 ? (
          <p className="text-sm text-[var(--rk-ink-muted)]">{to("noOrders")}</p>
        ) : (
          <AccountOrdersList
            orders={rows}
            labels={{
              all: to("filterAll"),
              active: to("filterActive"),
              done: to("filterDone"),
              empty: to("noOrders"),
            }}
          />
        )}
      </div>
    </div>
  );
}
