/* ==========================================================================
 * ADMIN NEXT — page-allhist.jsx  (แยกไฟล์ละหน้า; โหลดผ่าน <script type="text/babel">)
 * ========================================================================== */

/* ---------- ประวัติทั้งหมด (ฝาก+ถอน) — /history-all ---------- */
const ALL_STATUS={success:{t:"สำเร็จ",c:"success"},approved:{t:"สำเร็จ",c:"success"},paid:{t:"จ่ายแล้ว",c:"success"},pending:{t:"รอ",c:"warn"},rejected:{t:"ปฏิเสธ",c:"danger"},failed:{t:"ไม่สำเร็จ",c:"danger"}};

function AllHistoryPage({ toast }) {
  const [rows,setRows]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [q,setQ]=useState(""),[type,setType]=useState("all"),[range,setRange]=useState("7d"),[custom,setCustom]=useState({from:bkkDate(6),to:bkkDate(0)});
  const [page,setPage]=useState(1),[size,setSize]=useState(50);
  const debRef=useRef(null);
  const load=useCallback(async(query,tp,rg,cust)=>{ setLoading(true); setErr(null);
    try{ const {from,to}=rangeToDates(rg,cust); const p=new URLSearchParams({limit:"300",type:tp,from,to}); if(query)p.set("q",query);
      const d=await api("/history-all?"+p.toString()); setRows(Array.isArray(d)?d:[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail&&window.__nxAuthFail();} setErr(e.status===403?"ไม่มีสิทธิ์ดูประวัติทั้งหมด":(e.message||"โหลดไม่สำเร็จ")); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(q.trim(),type,range,custom); },[type,range,load]);
  useEffect(()=>{ if(debRef.current)clearTimeout(debRef.current); debRef.current=setTimeout(()=>load(q.trim(),type,range,custom),350); return ()=>clearTimeout(debRef.current); },[q]);
  useEffect(()=>{ setPage(1); },[q,type,range,rows.length]);
  const paged=rows.slice((page-1)*size,page*size);
  const doExport=()=>{ csvDownload("history-all-"+bkkDate(0)+".csv",[["เวลา","ประเภท","ยูส","ชื่อสมาชิก","ยอด(บาท)","ช่องทาง","สถานะ","ผู้ทำ"],...rows.map(r=>[fmtDT(r.created_at),r.type==="deposit"?"ฝาก":"ถอน",r.username,r.full_name,(Number(r.amount||0)/100).toFixed(2),r.method,r.status,r.operator_display_name||r.operator_name||""])]); toast("ส่งออกแล้ว"); };
  return (<div className="space-y-3">
    <HistToolbar q={q} setQ={setQ} range={range} setRange={setRange} custom={custom} setCustom={setCustom} onReload={()=>load(q.trim(),type,range,custom)} onExport={doExport} loading={loading} count={rows.length} placeholder="ค้นหา ชื่อ / ยูส / เบอร์…">
      <div className="flex flex-wrap items-center gap-1 rounded-lg border border-line bg-sunken p-0.5">
        {[["all","ทั้งหมด"],["deposit","ฝาก"],["withdraw","ถอน"]].map(([k,l])=>(<button key={k} onClick={()=>setType(k)} className={"rounded-md px-2.5 py-1 text-xs font-medium transition-colors "+(type===k?"bg-accent text-accent-fg shadow-sm":"text-fg-2 hover:text-fg")}>{l}</button>))}
      </div>
    </HistToolbar>
    {err ? <HistErr msg={err} onRetry={()=>load(q.trim(),type,range,custom)}/>
    : (<div className="overflow-hidden rounded-xl border border-line bg-surface shadow-sm"><div className="overflow-x-auto"><table className="w-full min-w-[900px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{histTh("เวลา")}{histTh("ประเภท")}{histTh("สมาชิก")}{histTh("ยอด","text-right")}{histTh("ช่องทาง")}{histTh("สถานะ")}{histTh("ผู้ทำ","pr-4")}</tr></thead>
      <tbody>
        {loading ? Array.from({length:8}).map((_,i)=>(<tr key={i} className="border-b border-line-soft"><td className="px-3 py-3" colSpan="7"><div className="skel h-5 w-full"/></td></tr>))
          : rows.length===0 ? (<tr><td colSpan="7" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ไม่มีรายการ</td></tr>)
          : paged.map((r,i)=>{ const isDep=r.type==="deposit"; const s=ALL_STATUS[String(r.status||"").toLowerCase()]||{t:r.status,c:"info"}; return (<tr key={(r.type||"")+(r.id||i)} className="border-b border-line-soft transition-colors last:border-0 hover:bg-sunken/50">
            <td className="whitespace-nowrap px-3 py-2.5 text-xs text-fg-2">{fmtDT(r.created_at)}</td>
            <td className="px-3"><Badge tone={isDep?"success":"danger"}>{isDep?"ฝาก":"ถอน"}</Badge></td>
            <td className="px-3"><div className="min-w-0"><div className="truncate font-semibold text-accent">{r.username||r.full_name||"-"}</div><div className="truncate text-[11px] text-muted">{r.full_name&&r.full_name!==r.username?r.full_name:""}</div></div></td>
            <td className="whitespace-nowrap px-3 text-right font-semibold tnum" style={{color:isDep?"var(--success)":"var(--danger)"}}>{isDep?"+":"-"}{money2(Math.abs(Number(r.amount||0)))}</td>
            <td className="px-3 text-xs text-fg-2">{isDep?(CHANNEL_LABEL[r.method]||r.method):bankName(r.method)}</td>
            <td className="px-3"><Badge tone={s.c}>{s.t}</Badge></td>
            <td className="pr-4 text-xs text-fg-2">{r.operator_display_name||r.operator_name||(r.operator_type==="auto"?"อัตโนมัติ":"-")}</td>
          </tr>); })}
      </tbody>
    </table></div>{!loading && !err && <Pager page={page} setPage={setPage} total={rows.length} size={size} setSize={setSize}/>}</div>)}
  </div>);
}
