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

/* ---------- รายงานเครดิต (Manual) — /reports/manual-adjustments ---------- */
const MADJ_KINDS=[["all","ทั้งหมด"],["manual_topup","เติมเงิน"],["admin_bonus","โบนัส"],["manual_deduct","ตัดเครดิต"],["turnover_sim","จำลองเทิร์น"],["turnover_reduce","ลดเทิร์น"]];

const MADJ_LABEL=Object.fromEntries(MADJ_KINDS);

const MADJ_TONE={manual_topup:"success",admin_bonus:"warn",manual_deduct:"danger",turnover_sim:"info",turnover_reduce:"info"};

function ManualReportPage({ toast }) {
  const [rows,setRows]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [kind,setKind]=useState("all");
  const [q,setQ]=useState("");
  const [range,setRange]=useState("");
  const [custom,setCustom]=useState({from:bkkDate(6),to:bkkDate(0)});
  const [page,setPage]=useState(1);
  const [size,setSize]=useState(50);
  const debRef=useRef(null);
  const load=useCallback(async(k,query,rg,cust)=>{
    setLoading(true); setErr(null);
    try{ const p=new URLSearchParams({limit:"300"}); if(k&&k!=="all")p.set("sub_kind",k); if(query)p.set("q",query);
      if(rg){ const {from,to}=rangeToDates(rg,cust); p.set("date_from",from); p.set("date_to",to); }
      const d=await api("/reports/manual-adjustments?"+p.toString()); setRows((d&&d.rows)||[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail&&window.__nxAuthFail();} setErr(e.status===403?"บัญชีนี้ไม่มีสิทธิ์ดูรายงานเครดิต":(e.message||"โหลดไม่สำเร็จ")); }
    finally{ setLoading(false); }
  },[]);
  useEffect(()=>{ load(kind,q.trim(),range,custom); },[kind,range,load]);
  useEffect(()=>{ if(debRef.current)clearTimeout(debRef.current); debRef.current=setTimeout(()=>load(kind,q.trim(),range,custom),350); return ()=>clearTimeout(debRef.current); },[q]);
  useEffect(()=>{ setPage(1); },[kind,q,range,rows.length]);
  const paged=rows.slice((page-1)*size,page*size);
  const doExport=()=>{ const H=["เวลา","สมาชิก","ยูส","ประเภท","ยอด(บาท)","ก่อน(บาท)","หลัง(บาท)","แอดมิน","หมายเหตุ"];
    const body=rows.map(r=>[fmtDT(r.created_at),r.username,r.full_name,MADJ_LABEL[r.sub_kind]||r.sub_kind,(Number(r.amount||0)/100).toFixed(2),(Number(r.credit_before||0)/100).toFixed(2),(Number(r.credit_after||0)/100).toFixed(2),r.admin_actor||"ระบบ",(r.meta&&r.meta.reason)||""]);
    csvDownload("manual-report-"+bkkDate(0)+".csv",[H,...body]); toast("ส่งออก "+rows.length+" รายการแล้ว"); };
  const H=({children,extra=""})=>(<th className={"whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2 "+extra}>{children}</th>);
  return (<div className="space-y-3">
    <div className="flex flex-wrap items-center gap-2">
      <div className="relative flex-1 sm:max-w-xs">
        <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted"><Ic d={I.search} size={16}/></span>
        <input value={q} onChange={(e)=>setQ(e.target.value)} placeholder="ค้นหา ชื่อ / ยูส / เบอร์…" className="h-9 w-full rounded-lg border border-line bg-surface pl-9 pr-3 text-sm text-fg placeholder:text-faint focus:border-accent focus:outline-none focus:ring-4 focus:ring-[var(--accent-ring)]"/>
      </div>
      <div className="flex flex-wrap items-center gap-1 rounded-lg border border-line bg-sunken p-0.5">
        {MADJ_KINDS.map(([k,l])=>(<button key={k} onClick={()=>setKind(k)} className={"rounded-md px-2.5 py-1 text-xs font-medium transition-colors "+(kind===k?"bg-accent text-accent-fg shadow-sm":"text-fg-2 hover:text-fg")}>{l}</button>))}
      </div>
      <div className="flex flex-wrap items-center gap-1 rounded-lg border border-line bg-sunken p-0.5">
        {FIN_RANGES.map(([k,l])=>(<button key={k||"none"} onClick={()=>setRange(k)} className={"rounded-md px-2 py-1 text-xs font-medium transition-colors "+(range===k?"bg-accent text-accent-fg shadow-sm":"text-fg-2 hover:text-fg")}>{l}</button>))}
      </div>
      {range==="custom" && (<div className="flex items-center gap-1.5">
        <input type="date" value={custom.from} onChange={(e)=>setCustom(c=>({...c,from:e.target.value}))} className="h-8 rounded-lg border border-line bg-surface px-2 text-xs"/>
        <span className="text-xs text-faint">-</span>
        <input type="date" value={custom.to} onChange={(e)=>setCustom(c=>({...c,to:e.target.value}))} className="h-8 rounded-lg border border-line bg-surface px-2 text-xs"/>
        <button onClick={()=>load(kind,q.trim(),"custom",custom)} className="h-8 rounded-lg bg-accent px-3 text-xs font-semibold text-accent-fg">ดู</button>
      </div>)}
      <button onClick={()=>load(kind,q.trim(),range,custom)} 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} cls={loading?"animate-spin":""}/> รีเฟรช</button>
      <ExportBtn onClick={doExport}/>
      <div className="ml-auto hidden text-xs text-muted sm:block tnum">{rows.length} รายการ</div>
    </div>
    {err ? (<div className="rounded-xl border border-line bg-surface px-4 py-16 text-center shadow-sm"><div className="mx-auto mb-2 grid h-10 w-10 place-items-center rounded-full text-danger" style={{background:"var(--danger-soft)"}}><Ic d={I.warn2} size={20}/></div><div className="text-sm font-medium text-fg-2">{err}</div><button onClick={()=>load(kind,q.trim(),range,custom)} className="mt-3 rounded-lg border border-line px-3 py-1.5 text-xs font-medium text-fg-2 hover:bg-sunken">ลองใหม่</button></div>)
    : (<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><H>เวลา</H><H>สมาชิก</H><H>ประเภท</H><H extra="text-right">ยอด</H><H extra="text-right">ก่อน→หลัง</H><H>แอดมิน</H><H>หมายเหตุ</H></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 neg=Number(r.amount||0)<0; return (<tr key={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"><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="px-3"><Badge tone={MADJ_TONE[r.sub_kind]||"info"}>{MADJ_LABEL[r.sub_kind]||r.sub_kind||"-"}</Badge></td>
            <td className="whitespace-nowrap px-3 text-right font-semibold tnum" style={{color:neg?"var(--danger)":"var(--success)"}}>{neg?"-":"+"}{money2(Math.abs(Number(r.amount||0)))}</td>
            <td className="whitespace-nowrap px-3 text-right tnum text-[11px] text-muted">{money2(r.credit_before)} → {money2(r.credit_after)}</td>
            <td className="px-3 text-xs text-fg-2">{r.admin_actor||"ระบบ"}</td>
            <td className="px-3 text-xs text-muted"><span className="truncate">{(r.meta&&r.meta.reason)||"-"}</span></td>
          </tr>); })}
      </tbody>
    </table></div>{!loading && !err && <Pager page={page} setPage={setPage} total={rows.length} size={size} setSize={setSize}/>}</div>)}
  </div>);
}
