import Link from "next/link";
import { notFound } from "next/navigation";
import { desc, eq } from "drizzle-orm";
import { db } from "@/db";
import { orders, orderItems, payments } from "@/db/schema";
import { ugx, fmtDate } from "@/lib/format";
import { activeGateways, ONLINE } from "@/lib/payments";
import { PayPanel } from "@/components/PayPanel";

export const metadata = { title: "Order Details", robots: { index: false } };
const STEPS = ["New", "Payment Confirmed", "Processing", "Packed", "Dispatched", "Out for Delivery", "Delivered"];

export default async function OrderPage({ params, searchParams }: { params: Promise<{ number: string }>; searchParams: Promise<{ new?: string; momo?: string; perr?: string; pay?: string }> }) {
  const { number } = await params; const sp = await searchParams;
  const [o] = await db.select().from(orders).where(eq(orders.number, number));
  if (!o) notFound();
  const items = await db.select().from(orderItems).where(eq(orderItems.orderId, o.id));
  const [lastPay] = await db.select().from(payments).where(eq(payments.orderId, o.id)).orderBy(desc(payments.id)).limit(1);
  const online = (await activeGateways()).filter((g) => ONLINE.includes(g.code)).map((g) => ({ code: g.code, name: g.name }));
  const paid = o.paymentStatus === "Paid";
  const closed = ["Cancelled", "Refunded", "Returned"].includes(o.status);
  const stepIdx = Math.max(0, STEPS.indexOf(o.status === "Awaiting Payment" || o.status === "Prescription Review Required" ? "New" : o.status));
  const payLabel = paid ? "Payment Successful" : lastPay?.status === "failed" ? "Payment Failed" : o.paymentMethod === "cod" ? "Pay on Delivery" : o.paymentMethod === "bank" ? "Awaiting Bank Transfer" : "Payment Pending";
  return (
    <div className="container-x py-10 max-w-5xl">
      {sp.new && <div className="card p-6 mb-6 bg-mint border-0 anim-fade-up"><h1 className="text-2xl font-extrabold text-brand">Thank you, {o.name.split(" ")[0]}! Your order has been received.</h1><p className="text-sm text-slate-600 mt-1">Keep your order number <b>{o.number}</b> to track your delivery.</p></div>}
      {sp.momo && <p className="mb-4 p-3 rounded-lg bg-amber-50 text-amber-800 text-sm">A payment prompt was sent to your phone. Approve it, then click “Check payment status”.</p>}
      {sp.perr && <p className="mb-4 p-3 rounded-lg bg-red-50 text-red-700 text-sm">Payment could not be started: {sp.perr}. You can retry below.</p>}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-6">
        <div><h2 className="section-title">Order {o.number}</h2><p className="text-sm text-slate-500">Placed {fmtDate(o.createdAt)}</p></div>
        <div className="flex gap-2"><span className="px-3 py-1.5 rounded-full text-xs font-bold bg-softblue text-royal">{o.status}</span><span className={`px-3 py-1.5 rounded-full text-xs font-bold ${paid ? "bg-mint text-brand" : lastPay?.status === "failed" ? "bg-red-50 text-red-600" : "bg-amber-50 text-amber-700"}`}>{payLabel}</span></div>
      </div>
      {!closed && (
        <div className="card p-6 mb-6 overflow-x-auto"><div className="flex min-w-[600px]">{STEPS.map((s, i) => <div key={s} className="flex-1 text-center relative"><div className={`mx-auto w-8 h-8 rounded-full grid place-items-center text-xs font-bold relative z-10 ${i <= stepIdx ? "bg-brand text-white" : "bg-cloud text-slate-400"}`}>{i + 1}</div>{i > 0 && <div className={`absolute top-4 right-1/2 w-full h-0.5 ${i <= stepIdx ? "bg-brand" : "bg-slate-200"}`} />}<div className="text-[11px] mt-2 font-semibold">{s}</div></div>)}</div></div>
      )}
      <div className="grid lg:grid-cols-[1fr_320px] gap-6">
        <div className="space-y-6">
          <div className="card p-6"><h3 className="font-bold mb-3">Items</h3>{items.map((i) => <div key={i.id} className="flex justify-between py-2 border-b text-sm"><span>{i.qty} × {i.name}</span><span className="font-semibold">{ugx(i.price * i.qty)}</span></div>)}
            <div className="text-sm space-y-1 mt-3"><div className="flex justify-between"><span>Subtotal</span><span>{ugx(o.subtotal)}</span></div>{o.discount > 0 && <div className="flex justify-between text-brand"><span>Discount</span><span>-{ugx(o.discount)}</span></div>}<div className="flex justify-between"><span>Delivery ({o.zoneName})</span><span>{ugx(o.shipping)}</span></div><div className="flex justify-between font-extrabold text-lg pt-2"><span>Total</span><span className="text-brand">{ugx(o.total)}</span></div></div>
          </div>
          <div className="card p-6"><h3 className="font-bold mb-3">Order history</h3>{[...o.history].reverse().map((h, k) => <div key={k} className="text-sm py-1.5 flex gap-3"><span className="text-slate-400 w-40 shrink-0">{fmtDate(h.at)}</span><span className="font-semibold">{h.status}</span>{h.note && <span className="text-slate-500">– {h.note}</span>}</div>)}</div>
        </div>
        <div className="space-y-4">
          <div className="card p-5 text-sm"><h3 className="font-bold mb-2">Delivery to</h3><p>{o.name}<br />{o.phone}<br />{o.address}, {o.town}, {o.district}</p>{o.directions && <p className="text-slate-500 mt-1">{o.directions}</p>}</div>
          {o.needsRx && <div className="card p-5 text-sm bg-softblue border-0"><b className="text-royal">Prescription required.</b> <Link href="/prescription" className="underline">Upload your prescription</Link> if you haven&apos;t already.</div>}
          {!paid && !closed && o.paymentMethod !== "cod" && o.paymentMethod !== "bank" && <PayPanel number={o.number} gateways={online} showVerify={!!lastPay} />}
        </div>
      </div>
    </div>
  );
}
