/* ==========================================================================
 * ADMIN NEXT — page-lineconnect.jsx  (LINE Connect)
 * ========================================================================== */

function LineConnectPage({ toast }) {
  const [tab,setTab]=useState("sessions"); // sessions | transactions | settings
  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="sessions" label="Sessions"/><Tb k="transactions" label="ธุรกรรม"/><Tb k="settings" label="ตั้งค่า"/></div>
    {tab==="sessions"&&<LineSessions toast={toast}/>}
    {tab==="transactions"&&<LineTransactions toast={toast}/>}
    {tab==="settings"&&<LineSettings toast={toast}/>}
  </div>);
}

function LineSessions({ toast }) {
  const [rows,setRows]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [status,setStatus]=useState(null);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{
      const [sess,st]=await Promise.all([
        api("/line-abd/sessions/local?include_inactive=true"),
        api("/line-abd/session/status").catch(()=>null)
      ]);
      setRows(Array.isArray(sess)?sess:sess.sessions||[]);
      setStatus(st);
    }catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);

  const disconnect=async(sid)=>{
    try{ await api("/line-abd/disconnect",{method:"POST",body:{session_id:sid}}); toast("ตัดการเชื่อมต่อแล้ว"); load(); }
    catch(e){ toast(e.message||"ไม่สำเร็จ"); }
  };

  const removeInactive=async()=>{
    try{ await api("/line-abd/sessions/remove-inactive",{method:"POST"}); toast("ลบ session ที่ไม่ใช้งานแล้ว"); load(); }
    catch(e){ toast(e.message||"ไม่สำเร็จ"); }
  };

  const [qrLoading,setQrLoading]=useState(false);
  const [qrData,setQrData]=useState(null);
  const createQr=async()=>{
    setQrLoading(true);
    try{ const d=await api("/line-abd/auth/qr/create",{method:"POST"}); setQrData(d); toast("สร้าง QR แล้ว — สแกนเพื่อเข้าสู่ระบบ"); }
    catch(e){ toast(e.message||"สร้าง QR ไม่สำเร็จ"); }
    finally{ setQrLoading(false); }
  };

  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">
    {status&&(<div className="rounded-xl border border-line bg-surface p-4 shadow-sm">
      <div className="flex items-center gap-2 text-sm"><span className="text-muted">สถานะ:</span><Badge color={status.connected?"green":"red"}>{status.connected?"เชื่อมต่อแล้ว":"ไม่ได้เชื่อมต่อ"}</Badge>
      {status.display_name&&<span className="font-medium">{status.display_name}</span>}</div>
    </div>)}

    <div className="flex flex-wrap items-center gap-3">
      <button onClick={createQr} disabled={qrLoading} className="flex h-9 items-center gap-1.5 rounded-lg bg-accent px-4 text-sm font-medium text-accent-fg hover:bg-accent-h disabled:opacity-50"><Ic d={I.plus} size={16}/> {qrLoading?"กำลังสร้าง…":"เชื่อมต่อใหม่ (QR)"}</button>
      <button onClick={removeInactive} 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">ลบ session ไม่ใช้งาน</button>
      <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>

    {qrData&&(<div className="rounded-xl border border-line bg-surface p-5 shadow-sm text-center space-y-3">
      <h3 className="text-sm font-semibold">สแกน QR Code เพื่อเข้าสู่ระบบ LINE</h3>
      {(qrData.callbackUrl||qrData.url)&&<img src={"https://api.qrserver.com/v1/create-qr-code/?size=200x200&data="+encodeURIComponent(qrData.callbackUrl||qrData.url)} alt="LINE QR" className="mx-auto rounded-lg" width={200} height={200}/>}
      {qrData.session&&<div className="text-xs text-muted mono">Session: {qrData.session}</div>}
      <button onClick={()=>setQrData(null)} className="text-xs text-muted hover:underline">ปิด</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">Display Name</th><th className="px-4 py-3">MID</th><th className="px-4 py-3">สถานะ</th><th className="px-4 py-3">Webhook</th><th className="px-4 py-3 text-right">จัดการ</th>
        </tr></thead>
        <tbody>{rows.length===0?(<tr><td colSpan={5} className="px-4 py-12 text-center text-muted">ไม่มี session</td></tr>):rows.map((r,i)=>(
          <tr key={r.session_id||i} className="border-b border-line last:border-0 hover:bg-sunken/40">
            <td className="px-4 py-3 font-medium">{r.display_name||"-"}</td>
            <td className="px-4 py-3 mono text-xs text-muted">{r.mid||"-"}</td>
            <td className="px-4 py-3"><Badge color={r.active?"green":"red"}>{r.active?"active":"inactive"}</Badge></td>
            <td className="px-4 py-3 text-xs text-muted truncate max-w-[200px]">{r.webhook_url||"-"}</td>
            <td className="px-4 py-3 text-right">
              <button onClick={()=>disconnect(r.session_id)} className="text-xs text-danger hover:underline">ตัดการเชื่อมต่อ</button>
            </td>
          </tr>))}</tbody>
      </table>
    </div>
  </div>);
}

function LineTransactions({ toast }) {
  const [rows,setRows]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [pulling,setPulling]=useState(false);

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

  const pull=async()=>{ setPulling(true);
    try{ const d=await api("/line-abd/transactions/pull",{method:"POST",body:{limit:50,mark_read:true}}); toast(`ดึงมา ${d.count||0} รายการ`); load(); }
    catch(e){ toast(e.message||"ดึงรายการไม่สำเร็จ"); }
    finally{ setPulling(false); } };

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

  return (<div className="space-y-4">
    <div className="flex flex-wrap items-center gap-3">
      <button onClick={pull} disabled={pulling} className="flex h-9 items-center gap-1.5 rounded-lg bg-accent px-4 text-sm font-medium text-accent-fg hover:bg-accent-h disabled:opacity-50">{pulling?"กำลังดึง…":"ดึงรายการใหม่"}</button>
      <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>

    {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 text-right">จำนวน</th><th className="px-4 py-3">จาก</th><th className="px-4 py-3">สถานะ</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,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||r.timestamp)}</td>
            <td className="px-4 py-3 text-right mono tnum font-medium">{baht(r.amount||0)}</td>
            <td className="px-4 py-3">{r.sender_name||r.from||"-"}</td>
            <td className="px-4 py-3"><Badge color={r.processed?"green":"yellow"}>{r.processed?"จับคู่แล้ว":"รอจับคู่"}</Badge></td>
          </tr>))}</tbody>
      </table>
    </div>)}
  </div>);
}

function LineSettings({ toast }) {
  const [cfg,setCfg]=useState({});
  const [loading,setLoading]=useState(true);
  const [saving,setSaving]=useState(false);
  const [err,setErr]=useState(null);
  const [usage,setUsage]=useState(null);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{
      const [s,u]=await Promise.all([api("/line-abd/settings"),api("/line-abd/usage").catch(()=>null)]);
      setCfg(s||{}); setUsage(u);
    }catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);

  const save=async()=>{ setSaving(true);
    try{ await api("/line-abd/settings",{method:"PATCH",body:cfg}); toast("บันทึกแล้ว"); }
    catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(false); } };
  const set=(k,v)=>setCfg(c=>({...c,[k]:v}));

  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}/>;

  const Lb=({children})=><label className="mb-1 block text-xs font-semibold text-fg-2">{children}</label>;

  return (<div className="space-y-5">
    {usage&&(<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
      {Object.entries(usage).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">{String(v)}</div>
        </div>))}
    </div>)}

    <div className="rounded-xl border border-line bg-surface p-5 shadow-sm space-y-4">
      <h3 className="text-sm font-semibold text-fg">ตั้งค่า LINE ABD</h3>
      <div><Lb>API Key</Lb><input type="text" value={cfg.api_key||""} onChange={e=>set("api_key",e.target.value)} placeholder="API Key" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm mono"/></div>
      <div><Lb>Webhook Secret</Lb><input type="text" value={cfg.webhook_secret||""} onChange={e=>set("webhook_secret",e.target.value)} placeholder="Webhook Secret" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm mono"/></div>
      <label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={cfg.auto_deposit===true||cfg.auto_deposit==="true"} onChange={e=>set("auto_deposit",e.target.checked)} className="h-4 w-4 rounded border-line accent-accent"/><span className="text-sm text-fg-2">เปิดฝากอัตโนมัติ</span></label>
    </div>

    <div className="flex justify-end"><button onClick={save} disabled={saving} className="rounded-lg bg-accent px-6 py-2.5 text-sm font-medium text-accent-fg hover:bg-accent-h disabled:opacity-50">{saving?"กำลังบันทึก…":"บันทึก"}</button></div>
  </div>);
}
