/* ==========================================================================
 * ADMIN NEXT — page-payment.jsx  (Payment — ช่องทางชำระเงิน)
 * ========================================================================== */

function PaymentPage({ toast }) {
  const [tab,setTab]=useState("providers"); // providers | transactions | autopeer
  const Tb=({k,label})=><button onClick={()=>setTab(k)} className={"rounded-lg px-4 py-2 text-sm font-medium transition-colors "+(tab===k?"bg-accent text-accent-fg":"text-fg-2 hover:bg-sunken")}>{label}</button>;

  return (<div className="space-y-5">
    <div className="flex gap-1 rounded-lg bg-sunken p-1"><Tb k="providers" label="ผู้ให้บริการ"/><Tb k="transactions" label="ธุรกรรม"/><Tb k="autopeer" label="รายการ Autopeer"/></div>
    {tab==="providers"&&<AutopeerProviderCard toast={toast} onShowList={()=>setTab("autopeer")}/>}
    {tab==="providers"&&<PaymentProviders toast={toast}/>}
    {tab==="transactions"&&<PaymentTransactions toast={toast}/>}
    {tab==="autopeer"&&<AutopeerDepositsPanel toast={toast} mode="payment"/>}
  </div>);
}

function PaymentProviders({ toast }) {
  const [rows,setRows]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [editing,setEditing]=useState(null);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{ const d=await api("/payment-providers"); setRows(Array.isArray(d)?d:d.rows||[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);

  const [saving,setSaving]=useState(false);
  const save=async(form)=>{ setSaving(true);
    try{
      if(form.id){ await api(`/payment-providers/${form.id}`,{method:"PATCH",body:form}); }
      else { await api("/payment-providers",{method:"POST",body:form}); }
      toast("บันทึกแล้ว"); setEditing(null); load();
    }catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(false); } };

  const [delId,setDelId]=useState(null);
  const del=async()=>{ if(!delId) return;
    try{ await api(`/payment-providers/${delId}`,{method:"DELETE"}); toast("ลบแล้ว"); setDelId(null); load(); }
    catch(e){ toast(e.message||"ลบไม่สำเร็จ"); } };

  if(loading) return <div className="flex items-center gap-2 py-16 justify-center text-sm text-muted"><Ic d={I.refresh} size={16} cls="animate-spin"/> กำลังโหลด…</div>;
  if(err) return <HistErr msg={err} onRetry={load}/>;

  return (<div className="space-y-4">
    <div className="flex items-center gap-3">
      <button onClick={load} className="flex h-9 items-center gap-1.5 rounded-lg border border-line bg-surface px-3 text-sm font-medium text-fg-2 hover:bg-sunken"><Ic d={I.refresh} size={16}/></button>
    </div>

    <div className="overflow-x-auto rounded-xl border border-line bg-surface shadow-sm">
      <table className="w-full text-sm">
        <thead><tr className="border-b border-line bg-sunken/60 text-left text-xs font-semibold text-muted">
          <th className="px-4 py-3">ชื่อ</th><th className="px-4 py-3">ประเภท</th><th className="px-4 py-3">เลขบัญชี</th><th className="px-4 py-3 text-right">จัดการ</th>
        </tr></thead>
        <tbody>{rows.length===0?(<tr><td colSpan={4} className="px-4 py-12 text-center text-muted">ไม่มีข้อมูล</td></tr>):rows.map(r=>(
          <tr key={r.id||r._id} className="border-b border-line last:border-0 hover:bg-sunken/40">
            <td className="px-4 py-3 font-medium">{r.name||"-"}</td>
            <td className="px-4 py-3 text-muted">{r.providerType||r.type||"-"}</td>
            <td className="px-4 py-3 mono">{r.accountNo||"-"}</td>
            <td className="px-4 py-3 text-right">
              {can("payment")&&<div className="flex items-center justify-end gap-2">
                <button onClick={()=>setEditing({...r,id:r.id||r._id})} className="text-xs text-accent hover:underline">แก้ไข</button>
                <button onClick={()=>setDelId(r.id||r._id)} className="text-xs text-danger hover:underline">ลบ</button>
              </div>}
            </td>
          </tr>))}</tbody>
      </table>
    </div>

    {editing&&(<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 fade-in" onClick={()=>setEditing(null)}>
      <div className="w-full max-w-md rounded-xl bg-surface p-6 shadow-lg pop" onClick={e=>e.stopPropagation()}>
        <h3 className="mb-4 text-sm font-semibold">{editing.id?"แก้ไข":"เพิ่ม"}ผู้ให้บริการ</h3>
        {[["name","ชื่อ"],["providerType","ประเภท"],["accountNo","เลขบัญชี"],["apiKey","API Key"],["apiSecret","API Secret"]].map(([k,l])=>(
          <div key={k} className="mb-3"><label className="mb-1 block text-xs font-semibold text-fg-2">{l}</label>
          <input type="text" value={editing[k]||""} onChange={e=>setEditing(p=>({...p,[k]:e.target.value}))} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>))}
        <div className="flex justify-end gap-2 mt-4">
          <button onClick={()=>setEditing(null)} className="rounded-lg border border-line px-4 py-2 text-sm text-fg-2 hover:bg-sunken">ยกเลิก</button>
          <button onClick={()=>save(editing)} disabled={saving} className="rounded-lg bg-accent px-4 py-2 text-sm font-medium text-accent-fg hover:bg-accent-h disabled:opacity-50">{saving?"...":"บันทึก"}</button>
        </div>
      </div>
    </div>)}

    {delId&&<SimpleConfirmModal title="ลบผู้ให้บริการ" msg="ยืนยันลบผู้ให้บริการนี้?" onOk={del} onCancel={()=>setDelId(null)}/>}
  </div>);
}

function PaymentTransactions({ toast }) {
  const [rows,setRows]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [range,setRange]=useState("today");
  const [summary,setSummary]=useState(null);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    const {from,to}=rangeToDates(range);
    try{
      const d=await api(`/payment-transactions?from=${from}&to=${to}&limit=200`);
      setRows(d.rows||[]); setSummary(d.summary||null);
    }catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ setLoading(false); } },[range]);
  useEffect(()=>{ load(); },[load]);

  if(err) return <HistErr msg={err} onRetry={load}/>;

  return (<div className="space-y-4">
    <div className="flex flex-wrap items-center gap-3">
      <select value={range} onChange={e=>setRange(e.target.value)} className="rounded-lg border border-line bg-surface px-3 py-2 text-sm">
        {RANGES.map(r=><option key={r[0]} value={r[0]}>{r[1]}</option>)}
      </select>
      <button onClick={load} className="flex h-9 items-center gap-1.5 rounded-lg border border-line bg-surface px-3 text-sm font-medium text-fg-2 hover:bg-sunken"><Ic d={I.refresh} size={16}/></button>
    </div>

    {summary&&(<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
      {Object.entries(summary).map(([k,v])=>(
        <div key={k} className="rounded-xl border border-line bg-surface p-3 shadow-sm">
          <div className="text-[11px] font-semibold text-muted uppercase">{k.replace(/_/g," ")}</div>
          <div className="mt-1 text-sm font-semibold mono tnum">{typeof v==="number"?baht(v):String(v)}</div>
        </div>))}
    </div>)}

    {loading ? <div className="flex items-center gap-2 py-16 justify-center text-sm text-muted"><Ic d={I.refresh} size={16} cls="animate-spin"/> กำลังโหลด…</div> : (
    <div className="overflow-x-auto rounded-xl border border-line bg-surface shadow-sm">
      <table className="w-full text-sm">
        <thead><tr className="border-b border-line bg-sunken/60 text-left text-xs font-semibold text-muted">
          <th className="px-4 py-3">วันที่</th><th className="px-4 py-3">ประเภท</th><th className="px-4 py-3">ผู้ให้บริการ</th><th className="px-4 py-3 text-right">จำนวน</th><th className="px-4 py-3">สถานะ</th>
        </tr></thead>
        <tbody>{rows.length===0?(<tr><td colSpan={5} className="px-4 py-12 text-center text-muted">ไม่มีข้อมูล</td></tr>):rows.map((r,i)=>(
          <tr key={i} className="border-b border-line last:border-0 hover:bg-sunken/40">
            <td className="px-4 py-3 text-muted whitespace-nowrap">{fmtDT(r.created_at||r.date)}</td>
            <td className="px-4 py-3"><Badge color={r.type==="deposit"?"green":"orange"}>{r.type||"-"}</Badge></td>
            <td className="px-4 py-3">{r.provider||r.provider_name||"-"}</td>
            <td className="px-4 py-3 text-right mono tnum">{baht(r.amount||0)}</td>
            <td className="px-4 py-3"><Badge color={r.status==="success"?"green":r.status==="pending"?"yellow":"red"}>{r.status||"-"}</Badge></td>
          </tr>))}</tbody>
      </table>
    </div>)}
  </div>);
}
