import type { Metadata } from "next";
import { redirect, notFound } from "next/navigation";
import Link from "next/link";
import { Reveal } from "../../../components/Reveal";
import { Footer } from "../../../components/Footer";
import { formatPrice, formatDate } from "../../../lib/format";
import { getSessionCustomer, getCustomerOrderDetail, customerOrderAction } from "../../../lib/customerAuth";
import { OrderActionButton } from "./components/OrderActionButton";
import { OrderStatusBadge } from "../../components/OrderStatusBadge";

export const metadata: Metadata = {
  title: "Bestelldetails",
  robots: { index: false, follow: true },
};

export default async function KontoBestellungDetailPage({ params }: { params: Promise<{ orderNumber: string }> }) {
  const { orderNumber } = await params;
  const session = await getSessionCustomer();
  if (!session) redirect("/konto/login");

  const order = await getCustomerOrderDetail(session.token, session.customer.id, decodeURIComponent(orderNumber));
  if (!order) notFound();

  const address =
    order.deliveryMethod === "address"
      ? order.street
      : `Packstation ${order.packstationNumber} · Postnummer ${order.postNumber}`;
  const action = customerOrderAction(order.status);

  return (
    <>
      <main className="flex flex-col flex-1 bg-bg-base">
        <Reveal className="flex flex-col gap-6 items-start pt-10 pb-16 px-[var(--layout-padding-x)] w-full max-w-[48rem] mx-auto">
          <Link href="/konto/bestellungen" className="text-body-sm text-text-muted hover:text-brand transition-colors">
            ← Zurück zur Bestellhistorie
          </Link>

          <p className="font-semibold text-h-feature text-text-primary" style={{ fontFamily: "var(--font-lora)" }}>
            {order.orderNumber}
          </p>

          <div className="flex flex-wrap gap-8 w-full">
            <div className="flex flex-col gap-1">
              <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">
              <p className="text-label text-text-muted">Status</p>
              <OrderStatusBadge status={order.status} />
            </div>
            <div className="flex flex-col gap-1">
              <p className="text-label text-text-muted">Zahlungsart</p>
              <p className="text-body-sm text-text-primary">{order.paymentMethodTitle}</p>
            </div>
          </div>

          <div className="flex flex-col gap-1 w-full">
            <p className="text-label text-text-muted">Lieferadresse</p>
            <p className="text-body-sm text-text-primary">
              {order.customerFirstName} {order.customerLastName}
            </p>
            <p className="text-body-sm text-text-primary">{address}</p>
            <p className="text-body-sm text-text-primary">
              {order.zip} {order.city}, {order.country}
            </p>
          </div>

          <div className="w-full bg-bg-base border border-border rounded-md p-6 flex flex-col gap-3">
            {order.items.map((item, i) => (
              <div key={i} className="flex items-start gap-4 w-full">
                <div className="flex-1 flex flex-col gap-0.5">
                  <p className="text-body-sm text-text-primary">
                    {item.quantity} × {item.productName}
                  </p>
                  {item.bundleContents && <p className="text-label text-text-muted">{item.bundleContents}</p>}
                  {item.returnQuantity > 0 && (
                    <p className="text-label text-text-muted">davon {item.returnQuantity} zurückgesendet</p>
                  )}
                </div>
                <p className="text-body-sm text-text-primary">{formatPrice(item.quantity * item.unitPrice)}</p>
              </div>
            ))}

            <div className="h-px bg-border w-full" />

            <div className="flex items-center w-full">
              <span className="text-body-sm text-text-primary">Zwischensumme</span>
              <span className="flex-1" />
              <span className="text-body-sm text-text-primary">{formatPrice(order.subtotal)}</span>
            </div>
            {order.discountCode && (
              <div className="flex items-center w-full">
                <span className="text-body-sm text-success">Rabattcode ({order.discountCode})</span>
                <span className="flex-1" />
                <span className="font-bold text-body-sm text-success">-{formatPrice(order.discountAmount)}</span>
              </div>
            )}
            <div className="flex items-center w-full">
              <span className="text-body-sm text-text-primary">Versand ({order.shippingMethodTitle})</span>
              <span className="flex-1" />
              <span className="text-body-sm text-text-primary">
                {order.shippingCost === 0 ? "Kostenlos" : formatPrice(order.shippingCost)}
              </span>
            </div>

            <div className="h-px bg-border w-full" />

            <div className="flex items-center w-full">
              <span className="font-semibold text-h4 text-text-primary" style={{ fontFamily: "var(--font-lora)" }}>
                Gesamtsumme
              </span>
              <span className="flex-1" />
              <span className="font-bold text-h-small text-text-primary">{formatPrice(order.total)}</span>
            </div>
          </div>

          {order.returnReason && (
            <div className="flex flex-col gap-1 w-full">
              <p className="text-label text-text-muted">Grund der Rücksendung</p>
              <p className="text-body-sm text-text-primary">{order.returnReason}</p>
            </div>
          )}

          <div className="flex flex-col gap-2 items-start">
            {order.invoiceNumber && (
              <a
                href={`/api/account/orders/${encodeURIComponent(order.orderNumber)}/invoice`}
                className="text-body-sm text-brand hover:underline"
              >
                Rechnung herunterladen ({order.invoiceNumber})
              </a>
            )}
            {order.correctionInvoiceNumber && (
              <a
                href={`/api/account/orders/${encodeURIComponent(order.orderNumber)}/correction-invoice`}
                className="text-body-sm text-brand hover:underline"
              >
                {order.status === "returned" ? "Gutschrift" : "Stornorechnung"} herunterladen ({order.correctionInvoiceNumber})
              </a>
            )}
          </div>

          {action && (
            <OrderActionButton
              orderNumber={order.orderNumber}
              action={action}
              items={order.items.map((item) => ({ product: item.product, productName: item.productName, quantity: item.quantity }))}
            />
          )}
        </Reveal>
      </main>
      <Footer />
    </>
  );
}
