import Link from "next/link";
import { and, desc, eq, ilike, or, type SQL } from "drizzle-orm";
import { db } from "@/db";
import { orders } from "@/db/schema";
import { ugx, fmtDate, ORDER_STATUSES } from "@/lib/format";
export default async function Orders({ searchParams }: { searchParams: Promise<{ q?: string; status?: string }> }) {
  const sp = await searchParams;
  const w: (SQL | undefined)[] = [];
  if (sp.q) w.push(or(ilike(orders.number, `%${sp.q}%`), ilike(orders.name, `%${sp.q}%`), ilike(orders.phone, `%${sp.q}%`)));
  if (sp.status) w.push(eq(orders.status, sp.status));
  const rows = await db.select().from(orders).where(and(...w)).orderBy(desc(orders.id)).limit(300);
  return (
    <div><div className="flex justify-between mb-4"><h1 className="text-2xl font-extrabold">Orders</h1><a href="/api/admin/export?type=orders" className="btn btn-outline !py-2">Export CSV</a></div>
      <form className="card p-4 flex flex-wrap gap-2 mb-4"><input name="q" defaultValue={sp.q} placeholder="Order #, name, phone" className="input !w-64" /><select name="status" defaultValue={sp.status} className="input !w-60"><option value="">All statuses</option>{ORDER_STATUSES.map((s) => <option key={s}>{s}</option>)}</select><button className="btn btn-blue !py-2">Filter</button></form>
      <div className="card overflow-x-auto"><table className="w-full text-sm"><thead className="bg-cloud text-xs text-left text-slate-500"><tr><th className="p-3">Order</th><th>Date</th><th>Customer</th><th>Method</th><th>Status</th><th>Payment</th><th className="text-right p-3">Total</th></tr></thead><tbody>
        {rows.map((o) => <tr key={o.id} className="border-t hover:bg-cloud"><td className="p-3"><Link href={`/admin/orders/${o.id}`} className="text-brand font-semibold">{o.number}</Link>{o.needsRx && <span className="ml-1 text-[10px] bg-softblue text-royal px-1 rounded">Rx</span>}</td><td className="text-xs">{fmtDate(o.createdAt)}</td><td>{o.name}<div className="text-xs text-slate-400">{o.phone}</div></td><td className="uppercase text-xs">{o.paymentMethod}</td><td><span className="px-2 py-0.5 rounded-full bg-softblue text-royal text-xs font-semibold">{o.status}</span></td><td className={o.paymentStatus === "Paid" ? "text-brand font-semibold" : "text-amber-600"}>{o.paymentStatus}</td><td className="text-right p-3 font-semibold">{ugx(o.total)}</td></tr>)}
      </tbody></table>{!rows.length && <p className="p-6 text-sm text-slate-500">No orders found.</p>}</div>
    </div>
  );
}
