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, ORDER_STATUSES } from "@/lib/format";
import { updateOrder, confirmOfflinePayment } from "@/app/admin/actions";
import { getSettings } from "@/lib/data";
import { PrintButton } from "@/components/PrintButton";
export default async function Order({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ print?: string }> }) {
  const id = Number((await params).id); const { print } = await searchParams;
  const [o] = await db.select().from(orders).where(eq(orders.id, id)); if (!o) notFound();
  const items = await db.select().from(orderItems).where(eq(orderItems.orderId, id));
  const pays = await db.select().from(payments).where(eq(payments.orderId, id)).orderBy(desc(payments.id));
  const s = await getSettings();
  const doc = (title: string, prices: boolean) => (
    <div className="card p-8 print:shadow-none print:border-0"><div className="flex justify-between"><div><div className="font-extrabold text-brand">{s.siteName}</div><div className="text-xs text-slate-500">{s.address}<br />{s.phones.join(" / ")} · {s.email}</div></div><div className="text-right"><div className="text-xl font-extrabold">{title}</div><div className="text-sm">{o.number}<br />{fmtDate(o.createdAt)}</div></div></div>
      <div className="mt-6 text-sm"><b>Ship to:</b> {o.name}, {o.phone}<br />{o.address}, {o.town}, {o.district}{o.directions && <> – {o.directions}</>}</div>
      <table className="w-full text-sm mt-6"><thead><tr className="border-b text-left"><th className="py-2">Item</th><th>Qty</th>{prices && <><th>Price</th><th className="text-right">Total</th></>}</tr></thead><tbody>{items.map((i) => <tr key={i.id} className="border-b"><td className="py-2">{i.name}</td><td>{i.qty}</td>{prices && <><td>{ugx(i.price)}</td><td className="text-right">{ugx(i.price * i.qty)}</td></>}</tr>)}</tbody></table>
      {prices && <div className="text-sm text-right mt-4 space-y-1"><div>Subtotal {ugx(o.subtotal)}</div>{o.discount > 0 && <div>Discount -{ugx(o.discount)}</div>}<div>Delivery {ugx(o.shipping)}</div><div className="font-extrabold text-lg">Total {ugx(o.total)}</div><div>Payment: {o.paymentStatus} ({o.paymentMethod.toUpperCase()})</div></div>}
    </div>
  );
  if (print) return <div className="max-w-3xl">{doc(print === "slip" ? "PACKING SLIP" : "INVOICE", print !== "slip")}<div className="mt-4 no-print"><PrintButton /></div></div>;
  return (
    <div className="grid xl:grid-cols-[2fr_1fr] gap-5">
      <div className="space-y-5">
        <div className="flex flex-wrap justify-between gap-2"><h1 className="text-2xl font-extrabold">Order {o.number}</h1><div className="flex gap-2"><a href={`?print=invoice`} className="btn btn-outline !py-2">Print invoice</a><a href={`?print=slip`} className="btn btn-outline !py-2">Packing slip</a></div></div>
        {o.needsRx && <div className="p-4 rounded-xl bg-softblue text-royal text-sm font-semibold">This order contains prescription-only items. A pharmacist must verify a valid prescription (see Prescription Management) before dispatch.</div>}
        <div className="card p-6"><table className="w-full text-sm"><tbody>{items.map((i) => <tr key={i.id} className="border-b"><td className="py-2">{i.name}</td><td>× {i.qty}</td><td className="text-right">{ugx(i.price * i.qty)}</td></tr>)}</tbody></table><div className="text-sm text-right mt-3 space-y-1"><div>Subtotal {ugx(o.subtotal)}</div><div>Discount -{ugx(o.discount)} {o.couponCode && `(${o.couponCode})`}</div><div>Delivery ({o.zoneName}) {ugx(o.shipping)}</div><div className="text-lg font-extrabold">Total {ugx(o.total)}</div></div></div>
        <div className="card p-6"><h3 className="font-bold mb-3">Payment transactions</h3>{pays.length ? pays.map((p) => <div key={p.id} className="flex justify-between text-sm border-b py-2"><span><b className="uppercase">{p.gateway}</b> · {p.reference}<span className="block text-xs text-slate-400">{fmtDate(p.createdAt)} {p.message}</span></span><span className={p.status === "successful" ? "text-brand font-bold" : p.status === "failed" ? "text-red-600 font-bold" : "text-amber-600 font-bold"}>{p.status} · {ugx(p.amount)}</span></div>) : <p className="text-sm text-slate-500">No transactions.</p>}
          {o.paymentStatus !== "Paid" && ["cod", "bank"].includes(o.paymentMethod) && <form action={confirmOfflinePayment} className="mt-3"><input type="hidden" name="id" value={o.id} /><button className="btn btn-green !py-2">Confirm {o.paymentMethod === "cod" ? "cash" : "bank transfer"} received</button></form>}
          {o.paymentStatus !== "Paid" && !["cod", "bank"].includes(o.paymentMethod) && <p className="text-xs text-slate-500 mt-3">Online payments are confirmed automatically only after server-side verification with the gateway.</p>}
        </div>
        <div className="card p-6"><h3 className="font-bold mb-3">History</h3>{[...o.history].reverse().map((h, k) => <div key={k} className="text-sm py-1"><span className="text-slate-400 mr-3">{fmtDate(h.at)}</span><b>{h.status}</b> {h.note && `– ${h.note}`}</div>)}</div>
      </div>
      <div className="space-y-5">
        <div className="card p-6 text-sm"><h3 className="font-bold mb-2">Customer</h3>{o.name}<br /><a href={`tel:${o.phone}`} className="text-brand">{o.phone}</a><br />{o.email}<br /><br /><b>Delivery</b><br />{o.address}, {o.town}, {o.district}<br />{o.directions}<br /><i>{o.instructions}</i>
          <div className="flex gap-2 mt-4"><a href={`https://wa.me/${o.phone.replace(/^0/, "256").replace(/\D/g, "")}?text=${encodeURIComponent(`Hello ${o.name}, update on your MARHATAB order ${o.number}: ${o.status}.`)}`} target="_blank" rel="noopener" className="btn bg-[#25D366] text-white !py-1.5 !text-xs">WhatsApp</a><a href={`mailto:${o.email}?subject=Order ${o.number}&body=Status: ${o.status}`} className="btn btn-outline !py-1.5 !text-xs">Email</a></div></div>
        <form action={updateOrder} className="card p-6 space-y-3"><h3 className="font-bold">Update order</h3><input type="hidden" name="id" value={o.id} />
          <label className="block"><span className="label">Status</span><select name="status" defaultValue={o.status} className="input">{ORDER_STATUSES.map((s) => <option key={s}>{s}</option>)}</select></label>
          <label className="block"><span className="label">Delivery personnel</span><input name="deliveryPerson" defaultValue={o.deliveryPerson} className="input" /></label>
          <label className="block"><span className="label">Note (shown to customer)</span><input name="note" className="input" /></label>
          <p className="text-xs text-slate-500">Cancelling/returning/refunding returns items to stock automatically. Refunds via the gateway must be issued in the provider dashboard; this records the refund.</p>
          <button className="btn btn-green w-full">Save</button></form>
      </div>
    </div>
  );
}
