import type { Metadata } from "next";
import { redirect, notFound } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { Reveal } from "../../../components/Reveal";
import { Footer } from "../../../components/Footer";
import { VatBreakdown } from "../../../components/VatBreakdown";
import { formatPrice, formatDate } from "../../../lib/format";
import { getSessionCustomer, getCustomerOrderDetail, customerOrderAction } from "../../../lib/customerAuth";
import { getProductImagesByIds, getPaymentMethods, groupPaymentMethodsForCheckout, getMediaUrlById } from "../../../lib/payload";
import { computeTaxBreakdown } from "@einfach-produktiv/invoicing";
import { buildTrackingUrl, CARRIER_LABELS, type Carrier } from "@einfach-produktiv/invoicing";
import { OrderActionButton } from "./components/OrderActionButton";
import { SwitchPaymentButton } from "./components/SwitchPaymentButton";
import { OrderStatusBadge } from "../../components/OrderStatusBadge";
import { PaymentStatusBadge } from "../../components/PaymentStatusBadge";

// Dynamic (was a static "Bestelldetails" title despite this being a
// per-order route) — just formats the already-known order number into
// the title, no extra fetch needed for a noindex account page.
export async function generateMetadata({
  params,
}: {
  params: Promise<{ orderNumber: string }>;
}): Promise<Metadata> {
  const { orderNumber } = await params;
  return {
    title: `Bestellung ${decodeURIComponent(orderNumber)}`,
    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), true);
  if (!order) notFound();

  const address =
    order.deliveryMethod === "address"
      ? order.street
      : `Packstation ${order.packstationNumber} · Postnummer ${order.postNumber}`;
  const shippingAddress =
    order.shippingDeliveryMethod === "packstation"
      ? `Packstation ${order.shippingPackstationNumber} · Postnummer ${order.shippingPostNumber}`
      : order.shippingStreet;
  const action = customerOrderAction(order.status);
  const imagesByProductId = await getProductImagesByIds(order.items.map((item) => item.product));
  const dhlReturnLabel = order.dhlReturnLabelMedia ? await getMediaUrlById(order.dhlReturnLabelMedia) : null;
  const taxBreakdown = computeTaxBreakdown(order.items, order.subtotal, order.discountAmount, order.shippingCost);
  // Same "Online-Zahlung" grouping/eligibility the switch-to-stripe route
  // itself re-checks authoritatively — only offer the button when it
  // would actually succeed.
  const canSwitchPayment =
    order.paymentProvider === "manual" &&
    order.status === "received" &&
    (order.paymentStatus === "pending" || order.paymentStatus === "not_applicable") &&
    groupPaymentMethodsForCheckout(await getPaymentMethods()).some((m) => m.provider === "stripe");

  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">Zahlungsstatus</p>
              <PaymentStatusBadge paymentStatus={order.paymentStatus} />
            </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>

          {order.trackingNumber && (
            <div className="flex flex-col gap-1 w-full">
              <p className="text-label text-text-muted">Sendungsverfolgung{order.carrier ? ` (${CARRIER_LABELS[order.carrier as Carrier] ?? order.carrier})` : ""}</p>
              {(() => {
                const trackingUrl = buildTrackingUrl(order.carrier, order.trackingNumber);
                return trackingUrl ? (
                  <a href={trackingUrl} target="_blank" rel="noopener noreferrer" className="text-body-sm text-brand hover:underline">
                    {order.trackingNumber}
                  </a>
                ) : (
                  <p className="text-body-sm text-text-primary">{order.trackingNumber}</p>
                );
              })()}
            </div>
          )}

          {dhlReturnLabel && (
            <div className="flex flex-col gap-1 w-full">
              <p className="text-label text-text-muted">DHL-Retourenschein{order.dhlReturnTrackingNumber ? ` (${order.dhlReturnTrackingNumber})` : ""}</p>
              <a href={dhlReturnLabel.url} target="_blank" rel="noopener noreferrer" className="text-body-sm text-brand hover:underline">
                Retourenschein herunterladen
              </a>
            </div>
          )}

          <div className="flex flex-col gap-1 w-full">
            {/* Labeled "Rechnungsadresse" only once there's an actual
                second (shipping) address to distinguish it from — the
                common case (no override) keeps the original "Lieferadresse"
                label, since that's exactly what this address still is. */}
            <p className="text-label text-text-muted">{order.hasDifferentShippingAddress ? "Rechnungsadresse" : "Lieferadresse"}</p>
            {order.companyName && (
              <p className="text-body-sm text-text-primary">{order.companyName}</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>
            {order.vatId && (
              <p className="text-body-sm text-text-muted">
                USt-IdNr. {order.vatId}
                {order.kleinunternehmer
                  ? " · Kleinunternehmer gem. § 19 UStG"
                  : order.vatExempt && " · steuerfreie innergemeinschaftliche Lieferung"}
              </p>
            )}
          </div>

          {order.hasDifferentShippingAddress && (
            <div className="flex flex-col gap-1 w-full">
              <p className="text-label text-text-muted">Lieferadresse</p>
              {order.shippingCompanyName && <p className="text-body-sm text-text-primary">{order.shippingCompanyName}</p>}
              <p className="text-body-sm text-text-primary">
                {order.shippingFirstName} {order.shippingLastName}
              </p>
              <p className="text-body-sm text-text-primary">{shippingAddress}</p>
              <p className="text-body-sm text-text-primary">
                {order.shippingZip} {order.shippingCity}, {order.shippingCountry}
              </p>
              {(order.shippingContactEmail || order.shippingContactPhone) && (
                <p className="text-body-sm text-text-muted">
                  {[order.shippingContactEmail, order.shippingContactPhone].filter(Boolean).join(" · ")}
                </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) => {
              const imageUrl = imagesByProductId.get(item.product);
              return (
              <div key={i} className="flex items-start gap-4 w-full">
                <div className="relative size-16 shrink-0 rounded-sm overflow-hidden bg-bg-muted">
                  {imageUrl && <Image src={imageUrl} alt="" fill sizes="64px" className="object-cover" />}
                </div>
                <div className="flex-1 flex flex-col gap-0.5">
                  <p className="text-body-sm text-text-primary">
                    {item.quantity} × {item.productName}
                    {item.variantName ? ` (${item.variantName})` : ""}
                  </p>
                  {!order.kleinunternehmer && <p className="text-label text-text-muted">inkl. {item.taxRatePercent}% MwSt.</p>}
                  {item.bundleContents && <p className="text-label text-text-muted">{item.bundleContents}</p>}
                  {item.sku && <p className="text-label text-text-muted">Art.-Nr. {item.sku}</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 flex-col gap-0.5 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>
              {order.kleinunternehmer ? (
                <p className="text-label text-text-muted">Gemäß § 19 UStG wird keine Umsatzsteuer berechnet.</p>
              ) : (
                <VatBreakdown groups={taxBreakdown} />
              )}
            </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 || canSwitchPayment) && (
            <div className="flex flex-wrap gap-3 items-start w-full">
              {action && (
                <OrderActionButton
                  orderNumber={order.orderNumber}
                  action={action}
                  items={order.items.map((item) => ({ product: item.product, productName: item.productName, quantity: item.quantity }))}
                />
              )}
              {canSwitchPayment && <SwitchPaymentButton orderNumber={order.orderNumber} />}
            </div>
          )}
        </Reveal>
      </main>
      <Footer />
    </>
  );
}
