"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";

export function PayPanel({ number, gateways, showVerify }: { number: string; gateways: { code: string; name: string }[]; showVerify: boolean }) {
  const r = useRouter();
  const [msg, setMsg] = useState(""); const [busy, setBusy] = useState(false); const [msisdn, setMsisdn] = useState("");
  async function call(body: object) {
    setBusy(true); setMsg("");
    const res = await fetch("/api/payments/start", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ number, ...body }) });
    const j = await res.json(); setBusy(false);
    if (j.redirect) { window.location.href = j.redirect; return; }
    if (j.error) setMsg(j.error);
    else if (j.message) setMsg(j.message);
    else if (j.status) { setMsg(j.status === "successful" ? "Payment confirmed!" : j.status === "failed" ? "Payment failed. You may try again." : "Payment is still pending."); r.refresh(); }
  }
  return (
    <div className="card p-5 space-y-3 no-print">
      <h3 className="font-bold">Complete payment</h3>
      {showVerify && <button disabled={busy} onClick={() => call({ action: "verify" })} className="btn btn-blue w-full">Check payment status</button>}
      {gateways.length > 0 && <>
        <input value={msisdn} onChange={(e) => setMsisdn(e.target.value)} placeholder="MoMo number (for MTN MoMo)" className="input" />
        <div className="grid gap-2">{gateways.map((g) => <button key={g.code} disabled={busy} onClick={() => call({ gateway: g.code, msisdn })} className="btn btn-outline w-full">Pay with {g.name}</button>)}</div>
      </>}
      {msg && <p className="text-sm bg-cloud p-3 rounded-lg">{msg}</p>}
    </div>
  );
}
