import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { getSettings } from "@/lib/settings";
import { FULFILLMENT_FLOW, FULFILLMENT_LABEL, PAYMENT_LABEL } from "@/lib/orders";
import { taka } from "@/lib/money";
import { fmtDate, fmtDateTime } from "@/lib/dates";
import ProofForm from "@/components/store/ProofForm";

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

export default async function OrderPage({ params, searchParams }: { params: Promise<{ number: string }>; searchParams: Promise<{ t?: string }> }) {
  const { number } = await params;
  const { t } = await searchParams;
  const [order, user, settings] = await Promise.all([
    db.order.findUnique({ where: { number }, include: { items: true, payments: { orderBy: { createdAt: "asc" } }, events: { where: { internal: false }, orderBy: { createdAt: "asc" } } } }),
    getCurrentUser(),
    getSettings(),
  ]);
  // Access: the private tracking link, or the signed-in owner.
  if (!order || !((t && t === order.trackingToken) || (user && order.userId === user.id))) notFound();

  const outstanding = Math.max(0, order.total - order.amountPaid);
  const pendingSubmitted = order.payments.filter((p) => p.status === "SUBMITTED").reduce((s, p) => s + p.amount, 0);
  const cancelled = order.fulfillmentStatus === "CANCELLED";
  const stepIdx = FULFILLMENT_FLOW.indexOf(order.fulfillmentStatus);
  const pay = settings.payments;
  const dest = order.paymentMethod === "BKASH" ? `bKash ${pay.bkash.accountType}: ${pay.bkash.number}` : order.paymentMethod === "NAGAD" ? `Nagad ${pay.nagad.accountType}: ${pay.nagad.number}` : order.paymentMethod === "BANK" ? pay.bank.details : null;
  const needsPayment = !cancelled && order.paymentPlan !== "COD" && outstanding - pendingSubmitted > 0;
  const nextAmount = order.amountPaid >= order.dueNow ? outstanding : Math.max(0, order.dueNow - order.amountPaid);

  return (
    <div className="wrap py-10 md:py-16 max-w-[1100px]">
      <p className="eyebrow-status">Order {order.number}</p>
      <h1 className="font-display text-[44px] md:text-[72px] leading-none mt-2">{cancelled ? "Order cancelled" : order.amountPaid >= order.dueNow && order.dueNow > 0 ? "Thank you" : "Order received"}</h1>
      <p className="mt-4 text-stone max-w-[60ch]">Placed {fmtDateTime(order.createdAt)}. Keep this page’s link, or use <Link href="/track" className="underline underline-offset-4">Track order</Link> with your order number and phone.</p>

      {!cancelled && (
        <ol className="mt-10 grid grid-cols-2 md:grid-cols-7 gap-y-4 gap-x-2" aria-label="Order progress">
          {FULFILLMENT_FLOW.map((s, i) => (
            <li key={s} aria-current={i === stepIdx ? "step" : undefined} className={`text-[13px] border-t-2 pt-2 ${i <= stepIdx ? "border-ink" : "border-sand text-stone"}`}>{FULFILLMENT_LABEL[s]}</li>
          ))}
        </ol>
      )}
      {cancelled && order.cancelReason && <p className="mt-6 border border-sand p-4">{order.cancelReason}</p>}

      <div className="grid md:grid-cols-12 gap-10 mt-12">
        <section className="md:col-span-7 space-y-10" aria-labelledby="pay">
          <div>
            <h2 id="pay" className="font-display text-[28px] mb-3">Payment</h2>
            <p>{PAYMENT_LABEL[order.paymentStatus]}.</p>
            <dl className="mt-3 grid grid-cols-[180px_1fr] gap-y-1.5 text-[15px]">
              <dt className="text-stone">Order total</dt><dd>{taka(order.total)}</dd>
              <dt className="text-stone">Verified payments</dt><dd>{taka(order.amountPaid)}</dd>
              {pendingSubmitted > 0 && <><dt className="text-stone">Awaiting verification</dt><dd>{taka(pendingSubmitted)}</dd></>}
              <dt className="text-stone">{order.paymentPlan === "COD" ? "Pay on delivery" : "Balance"}</dt><dd>{taka(outstanding)}{order.balanceDueAt && outstanding > 0 && order.paymentPlan === "DEPOSIT" ? ` · due by ${fmtDate(order.balanceDueAt)}` : ""}</dd>
            </dl>
            {order.paymentPlan === "COD" && !cancelled && <p className="mt-4 text-[14px] text-stone">Cash on delivery. We’ll confirm this order by phone before dispatch.</p>}
          </div>

          {needsPayment && dest && (
            <div className="border border-ink p-5 space-y-4">
              <h3 className="font-display text-[24px]">{order.amountPaid > 0 ? "Pay the balance" : "Send your payment"}</h3>
              <p>Send <strong className="font-medium">{taka(Math.min(nextAmount, outstanding - pendingSubmitted) || outstanding)}</strong> to <strong className="font-medium">{dest}</strong>, then enter the transaction ID below.</p>
              {order.holdExpiresAt && order.amountPaid === 0 && <p className="text-[14px] text-stone">Your items are held until {fmtDateTime(order.holdExpiresAt)}. After that the reservation is released.</p>}
              <ProofForm token={order.trackingToken} method={order.paymentMethod as "BKASH" | "NAGAD" | "BANK"} suggested={Math.min(nextAmount, outstanding - pendingSubmitted) || outstanding} />
            </div>
          )}

          {order.payments.length > 0 && (
            <div><h3 className="nav-type text-stone mb-2">Payment history</h3>
              <ul className="divide-y divide-sand border-y border-sand text-[14px]">{order.payments.map((p) => (
                <li key={p.id} className="py-2 flex justify-between gap-3"><span>{p.kind === "REFUND" ? "Refund" : "Payment"} · {p.method} {p.reference ?? ""}</span><span>{taka(p.amount)} · {p.status === "VERIFIED" ? "Verified" : p.status === "REJECTED" ? "Rejected" : "Awaiting verification"}</span></li>))}</ul></div>
          )}

          {order.hasPreorder && (
            <div><h3 className="nav-type text-stone mb-2">Pre-order terms you accepted</h3><p className="text-[14px] text-stone leading-relaxed">{settings.preorder.defaultTerms}{order.termsAcceptedAt ? ` Accepted ${fmtDateTime(order.termsAcceptedAt)}.` : ""}</p></div>
          )}
          {order.trackingNumber && <p><span className="text-stone">Courier:</span> {order.courier} · <span className="text-stone">Tracking:</span> {order.trackingNumber}</p>}
          <div><h3 className="nav-type text-stone mb-2">Updates</h3><ul className="text-[14px] space-y-1.5">{order.events.map((e) => <li key={e.id}><span className="text-stone">{fmtDateTime(e.createdAt)}</span> · {e.message}</li>)}</ul></div>
        </section>

        <section className="md:col-span-5" aria-labelledby="items">
          <h2 id="items" className="font-display text-[28px] mb-3">Items</h2>
          <ul className="divide-y divide-sand border-y border-sand">
            {order.items.map((it) => (
              <li key={it.id} className="py-4 flex gap-3">
                <div className="relative w-16 aspect-portrait bg-linen shrink-0">{it.imageUrl && <Image src={it.imageUrl} alt="" fill sizes="64px" className="object-cover" />}</div>
                <div className="flex-1 text-[14px]"><p>{it.productName} × {it.qty}</p><p className="text-stone">{it.variantLabel}</p>
                  {it.mode === "PRE_ORDER" ? <p className="eyebrow-status">Pre-order · batch {it.batchCode} · estimated dispatch {it.dispatchWindow}</p> : <p className="text-stone">Ready to ship</p>}</div>
                <span className="text-[14px]">{taka(it.lineTotal)}</span>
              </li>))}
          </ul>
          <dl className="mt-4 space-y-1 text-[14px]">
            <div className="flex justify-between"><dt>Subtotal</dt><dd>{taka(order.subtotal)}</dd></div>
            {order.discountTotal > 0 && <div className="flex justify-between"><dt>Discount</dt><dd>−{taka(order.discountTotal)}</dd></div>}
            <div className="flex justify-between"><dt>Delivery ({order.shippingZoneName})</dt><dd>{taka(order.shippingFee)}</dd></div>
            <div className="flex justify-between text-[16px] pt-2 border-t border-sand"><dt>Total</dt><dd>{taka(order.total)}</dd></div>
          </dl>
          {order.fulfillmentRule === "SHIP_SEPARATELY" && <p className="mt-4 text-[14px] text-stone">Shipping: ready items now, pre-order items when they arrive (two parcels).</p>}
          {order.hasPreorder && order.fulfillmentRule === "SHIP_TOGETHER" && order.items.some((i) => i.mode === "READY_STOCK") && <p className="mt-4 text-[14px] text-stone">Shipping: everything is dispatched together once the pre-order items arrive.</p>}
          <div className="mt-6 text-[14px] text-stone"><p>{order.customerName} · {order.phone}</p><p>{order.address}, {order.area}, {order.district}</p></div>
        </section>
      </div>
    </div>
  );
}
