import { desc, ilike, or, sql } from "drizzle-orm";
import { db } from "@/db";
import { customers } from "@/db/schema";
import { fmtDate } from "@/lib/format";
import { adjustPoints } from "@/app/admin/actions";
export default async function C({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
  const { q } = await searchParams;
  const rows = await db.select({ c: customers, orders: sql<number>`(select count(*)::int from orders o where o.customer_id = ${customers.id})`, spent: sql<number>`(select coalesce(sum(total),0)::int from orders o where o.customer_id = ${customers.id} and o.payment_status='Paid')` }).from(customers).where(q ? or(ilike(customers.name, `%${q}%`), ilike(customers.email, `%${q}%`), ilike(customers.phone, `%${q}%`)) : undefined).orderBy(desc(customers.id));
  return <div><h1 className="text-2xl font-extrabold mb-4">Customers</h1><form className="card p-4 mb-4 flex gap-2"><input name="q" defaultValue={q} placeholder="Search" className="input !w-72" /><button className="btn btn-blue !py-2">Search</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">Customer</th><th>Phone</th><th>Joined</th><th>Orders</th><th>Paid spend</th><th>Points</th><th className="p-3">Adjust points</th></tr></thead><tbody>
      {rows.map(({ c, orders, spent }) => <tr key={c.id} className="border-t"><td className="p-3"><b>{c.name}</b><div className="text-xs text-slate-400">{c.email}{c.newsletter && " · newsletter"}</div></td><td>{c.phone}</td><td className="text-xs">{fmtDate(c.createdAt)}</td><td>{orders}</td><td>UGX {spent.toLocaleString()}</td><td className="font-bold text-brand">{c.points}</td><td className="p-3"><form action={adjustPoints} className="flex gap-1"><input type="hidden" name="id" value={c.id} /><input name="points" type="number" placeholder="±" className="input !w-20 !py-1 !text-xs" /><input name="reason" placeholder="Reason" className="input !w-32 !py-1 !text-xs" /><button className="btn btn-green !py-1 !px-3 !text-xs">OK</button></form></td></tr>)}
    </tbody></table>{!rows.length && <p className="p-6 text-sm text-slate-500">No customers yet.</p>}</div></div>;
}
