import { canSee } from "@/lib/session";
import { getPortalSession } from "@/lib/get-session";
import { loadTenantForShell } from "@/lib/portal-data";
import { Panel } from "@/components/portal/Panel";
import { NotAllowed } from "@/components/portal/NotAllowed";

const EVENT_FILTERS = ["all", "auth", "scan", "finding", "evidence", "billing", "settings"];

export default async function AuditPage({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ q?: string; type?: string; product?: string }>;
}) {
  const { slug } = await params;
  const sp = await searchParams;
  const session = await getPortalSession();
  if (!canSee(session, "audit")) return <NotAllowed need="LEGAL / IT_ADMIN" />;
  const t = await loadTenantForShell(slug);
  if (!t) return null;

  const q = sp.q?.toLowerCase() ?? "";
  const type = sp.type ?? "all";
  const product = sp.product ?? "all";

  const rows = t.audit.filter((r) => {
    if (q && !`${r.event} ${r.actor} ${r.product}`.toLowerCase().includes(q)) return false;
    if (type !== "all" && !r.event.startsWith(type)) return false;
    if (product !== "all" && r.product !== product) return false;
    return true;
  });

  return (
    <div className="content-inner">
      <div className="page-head">
        <div>
          <div className="page-title">Audit log</div>
          <div className="page-sub">
            <span className="mono">{rows.length}</span> of <span className="mono">{t.audit.length}</span>{" "}
            events · retention 365 days · hash-chained
          </div>
        </div>
        <div className="ph-actions">
          <button type="button" className="btn">Export (CSV)</button>
        </div>
      </div>

      <Panel pad={false}>
        <form method="get" className="row" style={{ gap: 10, padding: "12px 14px", borderBottom: "1px solid var(--rule)", flexWrap: "wrap" }}>
          <input name="q" defaultValue={sp.q ?? ""} placeholder="Search events…" className="input mono" style={{ width: 260, fontSize: 12 }} />
          <span className="row" style={{ gap: 4 }}>
            {EVENT_FILTERS.map((f) => (
              <button key={f} name="type" value={f} type="submit" className={"btn btn-sm" + (type === f ? " btn-primary" : "")}>
                {f}
              </button>
            ))}
          </span>
          <span className="spacer" />
          <select name="product" defaultValue={product} className="input" style={{ width: 200, fontSize: 12 }}>
            <option value="all">All products</option>
            {t.products.filter((p) => t.entitled.includes(p.id)).map((p) => (
              <option key={p.id} value={p.id}>{p.name}</option>
            ))}
            <option value="—">platform / —</option>
          </select>
        </form>

        <table className="ltable">
          <thead>
            <tr>
              <th>When</th>
              <th>Event</th>
              <th>Actor</th>
              <th>Product</th>
              <th>Source IP</th>
              <th>Result</th>
            </tr>
          </thead>
          <tbody>
            {rows.slice(0, 50).map((r, i) => (
              <tr key={i}>
                <td className="mono t-dim" style={{ whiteSpace: "nowrap" }}>{r.date} {r.time}</td>
                <td className="mono" style={{ fontSize: 11.5 }}>{r.event}</td>
                <td>{r.actor}</td>
                <td className="mono t-dim">{r.product}</td>
                <td className="mono t-dim">{r.ip}</td>
                <td>
                  <span className="row" style={{ gap: 6, fontSize: 12 }}>
                    <span className={`dot ${r.result === "denied" ? "danger" : "ok"}`} />
                    {r.result === "denied" ? "DENIED" : "OK"}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Panel>
    </div>
  );
}
