/* ============================================================
   NeuroRoute — Request Log Explorer (1.1)
   Shared by the customer portal (org-scoped via auth) and the admin
   Customers "View logs" drill-in (orgId prop supplied).
   ============================================================ */
// filterParams maps the filter-bar state to backend query params — splits
// the single "key:value" tag input into the tag_key/tag_value pair the
// usage_events.metadata JSONB containment filter expects.
function filterParams(f){
  var out = {model:f.model, provider:f.provider, cached:f.cached, guardrail_action:f.guardrail_action, status:f.status};
  var tag = (f.tag||'').trim();
  if(tag){
    var i = tag.indexOf(':');
    if(i>0){ out.tag_key = tag.slice(0,i).trim(); out.tag_value = tag.slice(i+1).trim(); }
  }
  return out;
}

// keySourceLabel maps the raw usage_events.key_source to the customer-facing
// distinction: BYOK (the customer's own provider key) vs a SISL-managed
// platform provider key. "none" = no provider call (e.g. a guardrail block).
function keySourceLabel(s){
  if(s==='customer_key') return 'BYOK';
  if(s==='sisl_key') return 'Provider key';
  if(s==='none') return '—';
  return '—';
}

function LogsPage({orgId}){
  const [loading, setLoading] = React.useState(true);
  const [rows, setRows] = React.useState([]);
  const [nextCursor, setNextCursor] = React.useState('');
  const [loadingMore, setLoadingMore] = React.useState(false);
  const [filters, setFilters] = React.useState({model:'', provider:'', cached:'', guardrail_action:'', status:'', tag:''});
  const [detail, setDetail] = React.useState(null);   // selected row
  const [explain, setExplain] = React.useState(null); // routing/explain result for detail
  const [explainLoading, setExplainLoading] = React.useState(false);

  const fetchPage = React.useCallback((params, append)=>{
    const call = orgId ? NR_API.adminLogs(orgId, params) : NR_API.logs(params);
    return call.then(function(res){
      const logs = (res && res.logs) || [];
      setRows(function(prev){ return append ? prev.concat(logs) : logs; });
      setNextCursor((res && res.next_cursor) || '');
    });
  }, [orgId]);

  React.useEffect(()=>{
    setLoading(true);
    fetchPage(Object.assign({limit:50}, filterParams(filters)), false).finally(()=>setLoading(false));
  }, [orgId, filters.model, filters.provider, filters.cached, filters.guardrail_action, filters.status, filters.tag]); // eslint-disable-line

  const loadMore = ()=>{
    if(!nextCursor) return;
    setLoadingMore(true);
    fetchPage(Object.assign({limit:50, cursor:nextCursor}, filterParams(filters)), true).finally(()=>setLoadingMore(false));
  };

  const [content, setContent] = React.useState(null);
  const [contentLoading, setContentLoading] = React.useState(false);

  const openDetail = (row)=>{
    setDetail(row);
    setExplain(null);
    setExplainLoading(true);
    NR_API.routingExplain(row.request_id).then(function(res){
      setExplain(res || null);
      setExplainLoading(false);
    }).catch(()=>setExplainLoading(false));

    setContent(null);
    setContentLoading(true);
    const contentCall = orgId ? NR_API.adminLogContent(orgId, row.request_id) : NR_API.logContent(row.request_id);
    contentCall.then(function(res){
      setContent((res && res.available) ? res : null);
      setContentLoading(false);
    }).catch(()=>setContentLoading(false));
  };

  const setFilter = (k,v)=>setFilters(function(f){ return Object.assign({}, f, {[k]:v}); });
  const [tagInput, setTagInput] = React.useState('');
  const commitTag = ()=>setFilter('tag', tagInput);

  const providers = DATA.PROVIDERS;
  const guardrailBadge = (action)=>{
    if(!action) return null;
    return <Badge color={action==='block'?'red':action==='redact'?'amber':'purple'} style={{fontSize:10,marginLeft:6}}>{action}</Badge>;
  };

  return (
    <div className="grid" style={{gap:18}}>
      <PageHead desc="Every request routed through NeuroRoute — filter by model, provider, cache status, or guardrail outcome, then drill into any row for the full routing decision.">
        <div className="row" style={{gap:8,flexWrap:'wrap'}}>
          <select className="select" style={{minWidth:140}} value={filters.model} onChange={function(e){setFilter('model', e.target.value);}}>
            <option value="">All models</option>
            {DATA.MODELS.map(function(m){ return <option key={m.id} value={m.id}>{m.name}</option>; })}
          </select>
          <select className="select" style={{minWidth:140}} value={filters.provider} onChange={function(e){setFilter('provider', e.target.value);}}>
            <option value="">All providers</option>
            {providers.map(function(p){ return <option key={p.id} value={p.id}>{p.name}</option>; })}
          </select>
          <select className="select" style={{minWidth:120}} value={filters.cached} onChange={function(e){setFilter('cached', e.target.value);}}>
            <option value="">All</option>
            <option value="true">Cached only</option>
            <option value="false">Not cached</option>
          </select>
          <select className="select" style={{minWidth:140}} value={filters.guardrail_action} onChange={function(e){setFilter('guardrail_action', e.target.value);}}>
            <option value="">Any guardrail outcome</option>
            <option value="flag">Flagged</option>
            <option value="block">Blocked</option>
            <option value="redact">Redacted</option>
          </select>
          <select className="select" style={{minWidth:120}} value={filters.status} onChange={function(e){setFilter('status', e.target.value);}}>
            <option value="">Any status</option>
            <option value="success">Success</option>
            <option value="blocked">Blocked</option>
            <option value="error">Error</option>
          </select>
          <input className="input" style={{minWidth:160}} placeholder="tag: key:value" title="Filter by request metadata tag, e.g. team:checkout"
            value={tagInput} onChange={function(e){setTagInput(e.target.value);}}
            onBlur={commitTag} onKeyDown={function(e){ if(e.key==='Enter') commitTag(); }}/>
        </div>
      </PageHead>

      {loading ? <LoadingPage/> : rows.length===0 ?
        <EmptyState icon="search" title="No requests yet" desc="Requests routed through NeuroRoute will appear here — filterable by model, provider, cache status, and guardrail outcome."/> :
      <>
        <div className="card">
          <div className="scroll-x"><table className="table">
            <thead><tr>
              <th>Time</th><th>Actor</th><th>Workspace</th><th>Model</th><th>Provider</th><th>Task</th><th>Status</th>
              <th style={{textAlign:'right'}}>Tokens</th>
              <th style={{textAlign:'right'}}>Cost</th>
              <th style={{textAlign:'right'}}>Savings</th>
              <th>Flags</th>
            </tr></thead>
            <tbody>{rows.map(function(r){
              return (
                <tr key={r.request_id} style={{cursor:'pointer'}} onClick={function(){openDetail(r);}}>
                  <td className="faint mono" style={{fontSize:12}}>{new Date(r.created_at).toLocaleString()}</td>
                  <td className="faint" style={{fontSize:12,maxWidth:160,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={r.actor||''}>{r.actor||'—'}</td>
                  <td className="faint" style={{fontSize:12,maxWidth:120,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={r.workspace||''}>{r.workspace||'—'}</td>
                  <td>{DATA.modelById(r.model).name}</td>
                  <td><ProviderLogo id={r.provider} size={22}/></td>
                  <td className="faint">{r.task_type||'—'}</td>
                  <td><Badge color={r.status==='error'?'red':r.status==='blocked'?'amber':'green'} dot style={{fontSize:10}}>{r.status||'success'}</Badge></td>
                  <td className="num" style={{textAlign:'right'}}>{fmtNum(r.input_tokens+r.output_tokens)}</td>
                  <td className="num" style={{textAlign:'right'}}>{fmtUSD(r.provider_cost_usd,4)}</td>
                  <td className="num" style={{textAlign:'right',color:'var(--green)'}}>{fmtUSD(r.savings_usd,4)}</td>
                  <td>
                    {r.was_cached && <Badge color="cyan" style={{fontSize:10}}>cached</Badge>}
                    {r.was_failover && <Badge color="amber" style={{fontSize:10,marginLeft:6}}>failover</Badge>}
                    {guardrailBadge(r.guardrail_action)}
                  </td>
                </tr>
              );
            })}</tbody>
          </table></div>
          {nextCursor && <div style={{textAlign:'center',padding:'14px 0'}}>
            <button className="btn btn-soft btn-sm" disabled={loadingMore} onClick={loadMore}>
              {loadingMore?'Loading…':'Load more'}
            </button>
          </div>}
        </div>
      </>}

      {detail && <Modal title="Request detail" sub={detail.request_id} onClose={function(){setDetail(null);}}
        footer={<button className="btn btn-ghost" onClick={function(){setDetail(null);}}>Close</button>}>
        <div className="grid" style={{gap:14}}>
          <div className="row" style={{gap:24,flexWrap:'wrap'}}>
            <div><div className="faint" style={{fontSize:11,textTransform:'uppercase'}}>Actor</div><div style={{fontWeight:600}}>{detail.actor||'—'}</div></div>
            <div><div className="faint" style={{fontSize:11,textTransform:'uppercase'}}>Workspace</div><div style={{fontWeight:600}}>{detail.workspace||'—'}</div></div>
            <div><div className="faint" style={{fontSize:11,textTransform:'uppercase'}}>Model</div><div style={{fontWeight:600}}>{DATA.modelById(detail.model).name}</div></div>
            <div><div className="faint" style={{fontSize:11,textTransform:'uppercase'}}>Provider</div><div style={{fontWeight:600}}>{detail.provider}</div></div>
            <div><div className="faint" style={{fontSize:11,textTransform:'uppercase'}}>Strategy</div><div style={{fontWeight:600}}>{detail.routing_strategy}</div></div>
            <div><div className="faint" style={{fontSize:11,textTransform:'uppercase'}}>Key source</div><div style={{fontWeight:600}}>{keySourceLabel(detail.key_source)}</div></div>
            <div><div className="faint" style={{fontSize:11,textTransform:'uppercase'}}>Cost</div><div style={{fontWeight:600}}>{fmtUSD(detail.provider_cost_usd,4)}</div></div>
            <div><div className="faint" style={{fontSize:11,textTransform:'uppercase'}}>Savings</div><div style={{fontWeight:600,color:'var(--green)'}}>{fmtUSD(detail.savings_usd,4)}</div></div>
          </div>
          {(detail.key_name || detail.key_public_id) && <div>
            <div className="faint" style={{fontSize:11,textTransform:'uppercase',marginBottom:4}}>API key</div>
            <div style={{fontWeight:600}}>{detail.key_name||'—'}</div>
            {detail.key_public_id && <div className="mono faint" style={{fontSize:12,marginTop:2}}>{detail.key_public_id}</div>}
          </div>}
          {detail.actor_user_id && <div>
            <div className="faint" style={{fontSize:11,textTransform:'uppercase',marginBottom:4}}>User ID</div>
            <div className="mono" style={{fontSize:12}}>{detail.actor_user_id}</div>
          </div>}

          {detail.guardrails_applied && <div>
            <div className="faint" style={{fontSize:11,textTransform:'uppercase',marginBottom:4}}>Guardrails</div>
            <div>{detail.guardrails_applied.split(',').map(function(n){ return <Badge key={n} color="purple" style={{fontSize:11,marginRight:6}}>{n.trim()}</Badge>; })}
              {guardrailBadge(detail.guardrail_action)}
            </div>
          </div>}

          {detail.metadata && <div>
            <div className="faint" style={{fontSize:11,textTransform:'uppercase',marginBottom:4}}>Tags</div>
            <div className="codeblock" style={{fontSize:12,padding:'10px 12px'}}>{JSON.stringify(detail.metadata)}</div>
          </div>}

          {contentLoading ? <div className="faint" style={{fontSize:13}}>Checking for stored request content…</div> :
           content && <div>
            <div className="faint" style={{fontSize:11,textTransform:'uppercase',marginBottom:4}}>Request content <Badge color="amber" style={{fontSize:10,marginLeft:4}}>content-mode logging</Badge></div>
            <div className="codeblock" style={{fontSize:12,padding:'10px 12px',marginBottom:8}}>
              <div className="faint" style={{fontSize:11,textTransform:'uppercase',marginBottom:4}}>Prompt</div>
              <div style={{whiteSpace:'pre-wrap'}}>{content.prompt}</div>
            </div>
            <div className="codeblock" style={{fontSize:12,padding:'10px 12px'}}>
              <div className="faint" style={{fontSize:11,textTransform:'uppercase',marginBottom:4}}>Response</div>
              <div style={{whiteSpace:'pre-wrap'}}>{content.response}</div>
            </div>
          </div>}

          <div>
            <div className="faint" style={{fontSize:11,textTransform:'uppercase',marginBottom:4}}>Routing decision</div>
            {explainLoading ? <div className="faint" style={{fontSize:13}}>Loading…</div> :
             explain ? <div className="codeblock" style={{fontSize:12,padding:'10px 12px',maxHeight:220,overflowY:'auto'}}>{JSON.stringify(explain, null, 2)}</div> :
             <div className="faint" style={{fontSize:13}}>No routing explanation available for this request.</div>}
          </div>
        </div>
      </Modal>}
    </div>
  );
}

window.PAGES = Object.assign(window.PAGES||{}, {logs: LogsPage});
