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

/* ---------- ประวัติ SMS — /sms/messages ---------- */
const SMS_DIR={in:{t:"เข้า",c:"success"},out:{t:"ออก",c:"danger"}};

// เครื่อง/ผู้ส่งของ SMS ไม่ตรงกับที่ผูกไว้ในบัญชีรับเงิน (ผูกไว้เท่านั้นถึงเทียบ)
function smsSourceMismatch(r){
  const devBad=!!r.recipient_sms_device_id && r.device_id!==r.recipient_sms_device_id;
  const senderBad=!!r.recipient_sms_sender && r.sender!==r.recipient_sms_sender;
  if(!devBad&&!senderBad) return null;
  return "บัญชีนี้ผูกกับ "+[r.recipient_sms_device_id,r.recipient_sms_sender].filter(Boolean).join(" · ");
}

// แสดงเลขบัญชีแบบเดียวกับใน SMS (x + 6 หลักท้าย)
const smsAccTail=(no)=>{ const d=String(no||"").replace(/\D/g,""); return d?"x"+d.slice(-6):"-"; };

function SmsRecipientCell({ r }) {
  if(r.recipient_account_id) return (<div className="flex items-center gap-1.5">
    <BankLogo code={r.recipient_bank_code} size={18}/>
    <div className="min-w-0"><div className="mono text-xs text-fg-2">{smsAccTail(r.recipient_account_no)}</div>
      <div className="truncate text-[10px] text-faint">{r.recipient_account_name||""}</div></div>
  </div>);
  if(r.to_acc) return <span className="text-[11px] text-faint"><span className="mono">x{r.to_acc}</span> · ไม่พบบัญชี</span>;
  return <span className="text-xs text-faint">-</span>;
}

// ปุ่มแยกตามบัญชีรับเงิน (จำนวนในช่วงวันที่ที่เลือก)
function SmsAccountChips({ accounts, value, onChange }) {
  if(!accounts || accounts.length===0) return null;
  const total=accounts.reduce((s,a)=>s+Number(a.count||0),0);
  const chip=(key,active,children)=>(<button key={key} onClick={()=>onChange(key)}
    className={"flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors "+(active?"border-accent bg-accent text-accent-fg shadow-sm":"border-line bg-surface text-fg-2 hover:border-accent/40 hover:text-fg")}>{children}</button>);
  return (<div className="flex flex-wrap items-center gap-1.5">
    {chip("",value==="",<>ทุกบัญชี <span className="tnum opacity-80">{N(total)}</span></>)}
    {accounts.map(a=>a.account_id
      ? chip(a.account_id,value===a.account_id,<><BankLogo code={a.bank_code} size={16}/><span className="mono">{smsAccTail(a.account_no)}</span><span className="max-w-[120px] truncate opacity-80">{a.account_name||""}</span><span className="tnum opacity-80">{N(a.count)}</span></>)
      : chip("none",value==="none",<>จับคู่บัญชีไม่ได้ <span className="tnum opacity-80">{N(a.count)}</span></>))}
  </div>);
}

function SmsHistoryPage({ toast }) {
  const [rows,setRows]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [q,setQ]=useState(""),[kind,setKind]=useState(""),[range,setRange]=useState("7d"),[custom,setCustom]=useState({from:bkkDate(6),to:bkkDate(0)});
  // เปิดมาจากการ์ดสรุปยอดหน้าหลัก ("ดู SMS →") จะกรองบัญชีนั้นไว้ให้เลย
  const [accountId,setAccountId]=useState(()=>{ try{ const v=sessionStorage.getItem("nx_smshist_account")||""; sessionStorage.removeItem("nx_smshist_account"); return v; }catch{ return ""; } });
  const [accounts,setAccounts]=useState([]);
  const [page,setPage]=useState(1),[size,setSize]=useState(50);
  const debRef=useRef(null);
  const load=useCallback(async(query,kd,rg,cust,acc)=>{ setLoading(true); setErr(null);
    try{ const {from,to}=rangeToDates(rg,cust); const p=new URLSearchParams({limit:"300",from,to}); if(query)p.set("q",query); if(kd)p.set("kind",kd); if(acc)p.set("accountId",acc);
      const s=new URLSearchParams({from,to}); if(kd)s.set("kind",kd);
      const [d,byAcc]=await Promise.all([api("/sms/messages?"+p.toString()),api("/sms/messages/by-account?"+s.toString()).catch(()=>[])]);
      setRows(Array.isArray(d)?d:[]); setAccounts(Array.isArray(byAcc)?byAcc:[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail&&window.__nxAuthFail();} setErr(e.status===403?"ไม่มีสิทธิ์ดูประวัติ SMS":(e.message||"โหลดไม่สำเร็จ")); }
    finally{ setLoading(false); } },[]);
  const reload=()=>load(q.trim(),kind,range,custom,accountId);
  useEffect(()=>{ reload(); },[kind,range,accountId,load]);
  useEffect(()=>{ if(debRef.current)clearTimeout(debRef.current); debRef.current=setTimeout(reload,350); return ()=>clearTimeout(debRef.current); },[q]);
  useEffect(()=>{ setPage(1); },[q,kind,range,accountId,rows.length]);
  const paged=rows.slice((page-1)*size,page*size);
  return (<div className="space-y-3">
    <HistToolbar q={q} setQ={setQ} range={range} setRange={setRange} custom={custom} setCustom={setCustom} onReload={reload} 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">
        {[["","ทั้งหมด"],["bank","ธนาคาร"],["test","ทดสอบ"]].map(([k,l])=>(<button key={k||"all"} onClick={()=>setKind(k)} className={"rounded-md px-2 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>
    </HistToolbar>
    <SmsAccountChips accounts={accounts} value={accountId} onChange={setAccountId}/>
    {err ? <HistErr msg={err} onRetry={reload}/>
    : (<div className="overflow-hidden rounded-xl border border-line bg-surface shadow-sm"><div className="overflow-x-auto"><table className="w-full min-w-[1120px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{histTh("เวลา")}{histTh("ผู้ส่ง")}{histTh("เครื่อง")}{histTh("เข้าบัญชี")}{histTh("ยอด","text-right")}{histTh("ธนาคาร")}{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="9"><div className="skel h-5 w-full"/></td></tr>))
          : rows.length===0 ? (<tr><td colSpan="9" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ไม่มีรายการ</td></tr>)
          : paged.map((r,i)=>{ const dir=SMS_DIR[String(r.parsed_direction||"").toLowerCase()]; const mismatch=smsSourceMismatch(r); 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.received_at)}</td>
            <td className="px-3 text-xs text-fg-2">{r.sender||"-"}</td>
            <td className="px-3 text-xs"><div className="flex flex-wrap items-center gap-1"><span className="mono text-fg-2">{r.device_id||"-"}</span>{mismatch&&<span title={mismatch}><Badge tone="danger">ไม่ตรงที่ผูก</Badge></span>}</div></td>
            <td className="px-3 py-1.5"><SmsRecipientCell r={r}/></td>
            <td className="whitespace-nowrap px-3 text-right tnum font-semibold">{r.parsed_amount!=null?money2(r.parsed_amount):"-"}</td>
            <td className="px-3 text-xs text-fg-2">{r.parsed_bank||"-"}</td>
            <td className="px-3">{dir?<Badge tone={dir.c}>{dir.t}</Badge>:<span className="text-xs text-faint">-</span>}</td>
            <td className="px-3 text-xs text-fg-2">{r.matched_username?<span className="font-medium">{r.matched_username}</span>:<span className="text-faint">-</span>}</td>
            <td className="pr-4 text-[11px] text-muted"><span className="line-clamp-1">{r.message||"-"}</span></td>
          </tr>); })}
      </tbody>
    </table></div>{!loading && !err && <Pager page={page} setPage={setPage} total={rows.length} size={size} setSize={setSize}/>}</div>)}
  </div>);
}
