import { AdminShell, EmptyState, StatCard } from '../components/admin/admin-page.jsx';
import { search } from '../../lib/audit-search.js';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

const SOURCE_TONES = {
  audit_logs: 'mars',
  tool_egress: 'neutral',
  activity_log: 'neutral',
  artifacts: 'mars',
};

function formatTime(t) {
  if (!t) return '';
  try {
    return new Date(t).toLocaleString();
  } catch {
    return String(t);
  }
}

export default async function AuditPage({ searchParams }) {
  const sp = (await Promise.resolve(searchParams)) || {};
  const filters = {
    limit: 50,
    query: typeof sp.query === 'string' ? sp.query : '',
    project_id: typeof sp.project_id === 'string' ? sp.project_id : '',
    agent_id: typeof sp.agent_id === 'string' ? sp.agent_id : '',
    tool: typeof sp.tool === 'string' ? sp.tool : '',
  };

  const result = search({
    limit: filters.limit,
    query: filters.query || undefined,
    project_id: filters.project_id || undefined,
    agent_id: filters.agent_id || undefined,
    tool: filters.tool || undefined,
  });

  const sourceCounts = result.rows.reduce((acc, r) => {
    acc[r.source] = (acc[r.source] || 0) + 1;
    return acc;
  }, {});

  return (
    <AdminShell
      kicker="Audit"
      title="Audit search"
      description="Unified search across audit logs, tool egress, activity, and artifacts."
    >
      <section className="admin-stats">
        <StatCard label="Results" value={result.rows.length} />
        <StatCard label="Audit logs" value={sourceCounts.audit_logs || 0} />
        <StatCard label="Tool egress" value={sourceCounts.tool_egress || 0} />
        <StatCard label="Activity" value={sourceCounts.activity_log || 0} tone="mars" />
      </section>

      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Filters</span>
          <small>Combine fields to narrow the cross-source search.</small>
        </div>
        <form className="audit-filters" method="get">
          <label className="audit-field">
            <span className="panel-label">Query</span>
            <input
              type="text"
              name="query"
              defaultValue={filters.query}
              placeholder="Free text"
            />
          </label>
          <label className="audit-field">
            <span className="panel-label">Project</span>
            <input
              type="text"
              name="project_id"
              defaultValue={filters.project_id}
              placeholder="project_id"
            />
          </label>
          <label className="audit-field">
            <span className="panel-label">Agent</span>
            <input
              type="text"
              name="agent_id"
              defaultValue={filters.agent_id}
              placeholder="agent_id"
            />
          </label>
          <label className="audit-field">
            <span className="panel-label">Tool</span>
            <input
              type="text"
              name="tool"
              defaultValue={filters.tool}
              placeholder="tool_name"
            />
          </label>
          <div className="audit-actions">
            <button type="submit" className="admin-button">
              Search
            </button>
            <a className="admin-button secondary" href="/audit">
              Reset
            </a>
          </div>
        </form>
      </section>

      {result.rows.length ? (
        <section className="admin-card-list compact" data-page="audit">
          {result.rows.map((r) => (
            <div className="admin-record compact audit-row" key={`${r.source}-${r.id}`}>
              <div className="admin-record-top">
                <div>
                  <span className={`admin-pill ${SOURCE_TONES[r.source] || 'neutral'}`}>
                    {r.source.replace('_', ' ')}
                  </span>
                  <b className="audit-action">{r.action}</b>
                </div>
                <small className="audit-time">{formatTime(r.time)}</small>
              </div>
              {r.summary ? <p>{r.summary}</p> : null}
              <div className="audit-meta">
                {r.agent_id ? (
                  <small>
                    <span>agent</span> <code>{r.agent_id}</code>
                  </small>
                ) : null}
                {r.project_id ? (
                  <small>
                    <span>project</span> <code>{r.project_id}</code>
                  </small>
                ) : null}
                {r.tool ? (
                  <small>
                    <span>tool</span> <code>{r.tool}</code>
                  </small>
                ) : null}
              </div>
            </div>
          ))}
        </section>
      ) : (
        <EmptyState title="No matching events">
          Adjust the filters above or clear them to see the latest activity.
        </EmptyState>
      )}
    </AdminShell>
  );
}
