import { desc, eq } from "drizzle-orm";
import { db } from "@/db";
import { gateways, payments, orders, paymentEvents } from "@/db/schema";
import { REQUIRED, CAPABILITIES, isConfigured } from "@/lib/payments";
import { saveGateway, testGatewayAction } from "@/app/admin/actions";
import { ugx, fmtDate } from "@/lib/format";
import { getSettings } from "@/lib/data";
const COLORS: Record<string, string> = { flutterwave: "#F5A623", pesapal: "#0072BC", dpo: "#E3262E", mtn: "#FFCC00", cod: "#079B49", bank: "#22339C" };
export default async function Payments() {
  await getSettings();
  const gws = await db.select().from(gateways);
  const order = ["flutterwave", "pesapal", "dpo", "mtn", "cod", "bank"];
  gws.sort((a, b) => order.indexOf(a.code) - order.indexOf(b.code));
  const tx = await db.select({ p: payments, number: orders.number }).from(payments).leftJoin(orders, eq(orders.id, payments.orderId)).orderBy(desc(payments.id)).limit(50);
  const ev = await db.select().from(paymentEvents).orderBy(desc(paymentEvents.id)).limit(10);
  const base = process.env.APP_URL || "https://marhatabfamilypharma.com";
  return (
    <div><h1 className="text-2xl font-extrabold">Settings → Payment Gateways</h1><p className="text-sm text-slate-500 mb-5">Only gateways that are <b>enabled</b> and have <b>complete credentials</b> appear at checkout. Changes apply immediately. Secret fields are never displayed – leave blank to keep the stored value.</p>
      <div className="grid xl:grid-cols-2 gap-5">
        {gws.map((g) => { const ok = isConfigured(g); const live = g.enabled && ok; return (
          <form key={g.code} action={saveGateway} className="card p-6 space-y-3"><input type="hidden" name="code" value={g.code} />
            <div className="flex items-center gap-3"><div className="w-11 h-11 rounded-xl grid place-items-center font-extrabold text-sm" style={{ background: COLORS[g.code] + "22", color: COLORS[g.code] === "#FFCC00" ? "#8a6d00" : COLORS[g.code] }}>{g.name.slice(0, 2).toUpperCase()}</div><div className="flex-1"><div className="font-bold">{g.name}</div><div className="text-xs text-slate-500">{CAPABILITIES[g.code]}</div></div>
              <span className={`text-xs font-bold px-2 py-1 rounded-full ${live ? "bg-mint text-brand" : g.enabled ? "bg-amber-50 text-amber-700" : "bg-cloud text-slate-500"}`}>{live ? "Active at checkout" : g.enabled ? "Incomplete" : "Disabled"}</span></div>
            <label className="flex items-center gap-2 text-sm font-semibold"><input type="checkbox" name="enabled" defaultChecked={g.enabled} className="w-4 h-4 accent-[#079B49]" /> Enable {g.name}</label>
            {["flutterwave", "pesapal", "dpo", "mtn"].includes(g.code) && <label className="block"><span className="label">Environment</span><select name="mode" defaultValue={g.mode} className="input"><option value="sandbox">Sandbox / Test</option><option value="production">Production / Live</option></select></label>}
            {REQUIRED[g.code].map((f) => <label key={f.key} className="block"><span className="label">{f.label}{f.secret && g.config[f.key] ? " (stored ••••" + g.config[f.key].slice(-4) + ")" : ""}</span>{f.key === "instructions" ? <textarea name={f.key} defaultValue={g.config[f.key]} rows={3} className="input" /> : <input name={f.key} type={f.secret ? "password" : "text"} autoComplete="off" defaultValue={f.secret ? "" : g.config[f.key]} className="input" />}</label>)}
            {g.code === "mtn" && <label className="block"><span className="label">Sandbox currency (MTN sandbox uses EUR)</span><input name="sandboxCurrency" defaultValue={g.config.sandboxCurrency || "EUR"} className="input" /></label>}
            {["flutterwave", "pesapal", "dpo", "mtn"].includes(g.code) && <p className="text-xs text-slate-500 break-all">Webhook / callback URL: <code className="bg-cloud px-1">{base}/api/payments/{g.code}/callback</code></p>}
            {g.lastTest && <p className="text-xs bg-cloud p-2 rounded">Last test: {g.lastTest}</p>}
            <div className="flex gap-2"><button className="btn btn-green flex-1">Save Settings</button>{["flutterwave", "pesapal", "dpo", "mtn"].includes(g.code) && <button formAction={testGatewayAction} disabled={!ok} className="btn btn-outline">Test connection</button>}</div>
          </form>); })}
      </div>
      <div className="card p-6 mt-6 overflow-x-auto"><h3 className="font-bold mb-3">Transaction history</h3><table className="w-full text-sm"><thead className="text-xs text-left text-slate-500"><tr><th className="py-2">Date</th><th>Order</th><th>Gateway</th><th>Reference</th><th>Status</th><th className="text-right">Amount</th></tr></thead><tbody>{tx.map(({ p, number }) => <tr key={p.id} className="border-t"><td className="py-2 text-xs">{fmtDate(p.createdAt)}</td><td>{number}</td><td className="uppercase text-xs font-bold">{p.gateway}</td><td className="text-xs">{p.reference}<div className="text-slate-400">{p.message}</div></td><td className={p.status === "successful" ? "text-brand font-bold" : p.status === "failed" ? "text-red-600 font-bold" : "text-amber-600 font-bold"}>{p.status}</td><td className="text-right">{ugx(p.amount)}</td></tr>)}</tbody></table>{!tx.length && <p className="text-sm text-slate-500">No transactions yet.</p>}</div>
      <div className="card p-6 mt-5"><h3 className="font-bold mb-3">Recent webhook / callback events</h3>{ev.map((e) => <div key={e.id} className="text-xs border-b py-1.5"><b className="uppercase">{e.gateway}</b> {e.reference} · {fmtDate(e.createdAt)}</div>)}{!ev.length && <p className="text-sm text-slate-500">None yet.</p>}</div>
    </div>
  );
}
