/* ==========================================================================
 * ADMIN NEXT — page-slipapprove.jsx  (อนุมัติสลิป)
 * ========================================================================== */

function SlipApprovePage({ toast }) {
  const [rows,setRows]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [q,setQ]=useState("");
  const [acting,setActing]=useState(null);

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

  const approve=async(r)=>{
    setActing(r.id||r._id);
    try{ await api(`/deposits/${r.id||r._id}/approve`,{method:"POST",body:{}}); toast("อนุมัติแล้ว"); load(); }
    catch(e){ toast(e.message||"อนุมัติไม่สำเร็จ"); }
    finally{ setActing(null); }
  };
  const [rejectId,setRejectId]=useState(null);
  const [rejectReason,setRejectReason]=useState("");
  const reject=async()=>{
    if(!rejectId) return;
    setActing(rejectId);
    try{ await api(`/deposits/${rejectId}/reject`,{method:"POST",body:{reason:rejectReason}}); toast("ปฏิเสธแล้ว"); setRejectId(null); setRejectReason(""); load(); }
    catch(e){ toast(e.message||"ปฏิเสธไม่สำเร็จ"); }
    finally{ setActing(null); }
  };

  const [detail,setDetail]=useState(null);
  const showDetail=async(r)=>{
    try{ const d=await api(`/deposits/${r.id||r._id}/detail`); setDetail(d); }
    catch(e){ toast(e.message||"โหลดไม่สำเร็จ"); }
  };

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

  return (<div className="space-y-4">
    <div className="flex flex-wrap items-center gap-3">
      <input type="text" value={q} onChange={e=>setQ(e.target.value)} placeholder="ค้นหา username / เลขบัญชี" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm w-56"/>
      <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>
      <span className="text-xs text-muted">รอดำเนินการ {rows.length} รายการ</span>
    </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">Username</th><th className="px-4 py-3">ช่องทาง</th><th className="px-4 py-3 text-right">จำนวน</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={6} className="px-4 py-12 text-center text-muted">ไม่มีรายการรออนุมัติ</td></tr>):rows.map(r=>{
          const id=r.id||r._id;
          return(<tr key={id} 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 font-medium">{r.username||r.phone||"-"}</td>
            <td className="px-4 py-3 text-muted">{r.channel||r.bank||"-"}</td>
            <td className="px-4 py-3 text-right mono tnum font-medium">{baht(r.amount||0)}</td>
            <td className="px-4 py-3"><Badge color="yellow">{r.status||"pending"}</Badge></td>
            <td className="px-4 py-3 text-right">
              <div className="flex items-center justify-end gap-2">
                <button onClick={()=>showDetail(r)} className="text-xs text-accent hover:underline">ดู</button>
                {canAny(["deposits","tool_slip_approve"])&&<><button onClick={()=>approve(r)} disabled={acting===id} className="rounded-lg bg-success px-3 py-1.5 text-xs font-medium text-white hover:opacity-90 disabled:opacity-50">อนุมัติ</button>
                <button onClick={()=>{setRejectId(id);setRejectReason("");}} className="rounded-lg bg-danger px-3 py-1.5 text-xs font-medium text-white hover:opacity-90">ปฏิเสธ</button></>}
              </div>
            </td>
          </tr>);})}</tbody>
      </table>
    </div>)}

    {rejectId&&(<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 fade-in" onClick={()=>setRejectId(null)}>
      <div className="w-full max-w-sm rounded-xl bg-surface p-6 shadow-lg pop" onClick={e=>e.stopPropagation()}>
        <h3 className="mb-3 text-sm font-semibold">ปฏิเสธรายการฝาก</h3>
        <input type="text" value={rejectReason} onChange={e=>setRejectReason(e.target.value)} placeholder="เหตุผล (ถ้ามี)" className="mb-4 w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>
        <div className="flex justify-end gap-2">
          <button onClick={()=>setRejectId(null)} className="rounded-lg border border-line px-4 py-2 text-sm text-fg-2 hover:bg-sunken">ยกเลิก</button>
          <button onClick={reject} disabled={acting===rejectId} className="rounded-lg bg-danger px-4 py-2 text-sm font-medium text-white hover:opacity-90 disabled:opacity-50">ยืนยันปฏิเสธ</button>
        </div>
      </div>
    </div>)}

    {detail&&(<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 fade-in" onClick={()=>setDetail(null)}>
      <div className="w-full max-w-lg rounded-xl bg-surface p-6 shadow-lg pop" onClick={e=>e.stopPropagation()}>
        <div className="mb-4 flex items-center justify-between"><h3 className="text-sm font-semibold">รายละเอียดรายการฝาก</h3><IconBtn icon={I.x} onClick={()=>setDetail(null)}/></div>
        <div className="space-y-2 text-sm">
          {Object.entries(detail).filter(([k])=>!k.startsWith("_")).map(([k,v])=>(
            <div key={k} className="flex justify-between gap-4"><span className="text-muted">{k}</span><span className="font-medium text-right break-all">{typeof v==="object"?JSON.stringify(v):String(v??"")}</span></div>
          ))}
        </div>
      </div>
    </div>)}
  </div>);
}
