import type { Metadata } from "next";
import { Suspense } from "react";
import { redirect } from "next/navigation";
import Link from "next/link";
import { Reveal } from "../../components/Reveal";
import { formatPrice, formatDate } from "../../lib/format";
import {
  getSessionCustomer,
  getCustomerOrders,
  getCustomerOrderYears,
  ORDER_STATUS_LABEL,
} from "../../lib/customerAuth";
import { getOrderFilterEnabled } from "../../lib/payload";
import { OrderStatusBadge } from "../components/OrderStatusBadge";
import { PaymentStatusBadge } from "../components/PaymentStatusBadge";
import { KontoShell } from "../components/KontoShell";
import { AccountIdentity } from "../components/AccountIdentity";
import { OrderFilters } from "./components/OrderFilters";

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

// Mirrors PaymentStatusBadge's own grouping ("Offen" covers both
// not_applicable and pending) — see getCustomerOrders's OPEN_PAYMENT_STATUSES.
const PAYMENT_STATUS_FILTER_LABEL: Record<string, string> = {
  open: "Offen",
  paid: "Bezahlt",
  failed: "Fehlgeschlagen",
  refunded: "Erstattet",
  partially_refunded: "Teilweise erstattet",
};

const STATUS_OPTIONS = Object.entries(ORDER_STATUS_LABEL).map(([value, label]) => ({ value, label }));
const PAYMENT_STATUS_OPTIONS = Object.entries(PAYMENT_STATUS_FILTER_LABEL).map(([value, label]) => ({ value, label }));

export default async function KontoBestellungenPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; paymentStatus?: string; year?: string }>;
}) {
  const session = await getSessionCustomer();
  if (!session) redirect("/konto/login");

  const orderFilterEnabled = await getOrderFilterEnabled();
  const rawSearchParams = await searchParams;
  const status = orderFilterEnabled ? rawSearchParams.status : undefined;
  const paymentStatus = orderFilterEnabled ? rawSearchParams.paymentStatus : undefined;
  const year = orderFilterEnabled ? rawSearchParams.year : undefined;

  const [orders, availableYears] = await Promise.all([
    getCustomerOrders(session.token, session.customer.id, true, { status, paymentStatus, year }),
    getCustomerOrderYears(session.token, session.customer.id),
  ]);

  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 Bestellungen
            </p>
            <AccountIdentity email={session.customer.email} customerNumber={session.customer.customerNumber} />
          </div>

          {orderFilterEnabled && availableYears.length > 0 && (
            <Suspense fallback={null}>
              <OrderFilters statusOptions={STATUS_OPTIONS} paymentStatusOptions={PAYMENT_STATUS_OPTIONS} years={availableYears} />
            </Suspense>
          )}

          {availableYears.length === 0 ? (
            <p className="text-body text-text-muted">Du hast noch keine Bestellung aufgegeben.</p>
          ) : orders.length === 0 ? (
            <p className="text-body text-text-muted">Keine Bestellungen gefunden, die zu den gewählten Filtern passen.</p>
          ) : (
            <div className="flex flex-col gap-4 w-full">
              {orders.map((order) => (
                <Link
                  key={order.orderNumber}
                  href={`/konto/bestellungen/${encodeURIComponent(order.orderNumber)}`}
                  className="grid grid-cols-2 sm:grid-cols-4 gap-x-3 sm:gap-x-6 gap-y-4 w-full bg-bg-base border border-border rounded-md p-6 hover:border-brand transition-colors"
                >
                  {/* Below sm (640px): 2 columns, plain DOM order —
                      Bestellnummer/Datum, Status/Zahlungsstatus,
                      Artikel/Gesamtbetrag tile into exactly those 3 pairs
                      on their own, no explicit placement needed. From sm
                      up: 4 columns, every cell explicitly pinned to a
                      row+column (sm:row-start-N sm:col-start-N) rather
                      than relying on `order` + Grid's auto-placement —
                      mixing `order` with only SOME items explicitly
                      positioned is a real footgun: the auto-placement
                      cursor for the un-pinned items starts scanning from
                      column 1 again regardless of what's already
                      explicitly placed elsewhere. Pinning every cell's row
                      AND column explicitly removes that ambiguity
                      entirely. Row 1: Bestellnummer/Datum in columns 1-2,
                      left-aligned (centering them in columns 2-3 was
                      tried and reverted — not wanted). Row 2: Artikel/
                      Status/Zahlungsstatus/Gesamtbetrag fill all 4
                      columns. */}
                  <div className="flex flex-col gap-1 sm:row-start-1 sm:col-start-1">
                    <p className="text-label text-text-muted">Bestellnummer</p>
                    <p className="font-bold text-body-sm text-text-primary">{order.orderNumber}</p>
                  </div>
                  <div className="flex flex-col gap-1 sm:row-start-1 sm:col-start-2">
                    <p className="text-label text-text-muted">Datum</p>
                    <p className="text-body-sm text-text-primary">{formatDate(order.createdAt)}</p>
                  </div>
                  <div className="flex flex-col gap-1 sm:row-start-2 sm:col-start-2">
                    <p className="text-label text-text-muted">Status</p>
                    <OrderStatusBadge status={order.status} />
                  </div>
                  <div className="flex flex-col gap-1 sm:row-start-2 sm:col-start-3">
                    <p className="text-label text-text-muted">Zahlungsstatus</p>
                    <PaymentStatusBadge paymentStatus={order.paymentStatus} />
                  </div>
                  <div className="flex flex-col gap-1 sm:row-start-2 sm:col-start-1">
                    <p className="text-label text-text-muted">Artikel</p>
                    <p className="text-body-sm text-text-primary">{order.itemCount}</p>
                  </div>
                  <div className="flex flex-col gap-1 sm:row-start-2 sm:col-start-4">
                    <p className="text-label text-text-muted">Gesamtbetrag</p>
                    <p className="font-bold text-body-sm text-text-primary">{formatPrice(order.total)}</p>
                  </div>
                </Link>
              ))}
            </div>
          )}

      </Reveal>
    </KontoShell>
  );
}
