import { useEffect, useState } from "react";
import { api } from "../api.js";

interface AuditLog {
  id: string;
  actorUserId: string | null;
  actorType: string;
  action: string;
  targetType: string | null;
  targetId: string | null;
  createdAt: string;
}

export function AuditLogsPage() {
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [filter, setFilter] = useState("");
  const [error, setError] = useState<string | null>(null);

  const load = (action = "") => {
    api<{ logs: AuditLog[] }>(`/admin/v1/audit-logs?action=${encodeURIComponent(action)}`)
      .then((r) => setLogs(r.logs))
      .catch((e) => setError(String(e.message)));
  };
  useEffect(() => load(), []);

  return (
    <div>
      <h2>Audit logs</h2>
      <div className="row" style={{ marginBottom: "1rem" }}>
        <input
          placeholder="Filtrera på action …"
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && load(filter)}
        />
        <button className="ghost" onClick={() => load(filter)}>
          Filtrera
        </button>
      </div>
      {error && <div className="error-text">{error}</div>}
      <div className="panel">
        <table>
          <thead>
            <tr>
              <th>Tid</th>
              <th>Aktör</th>
              <th>Typ</th>
              <th>Action</th>
              <th>Mål</th>
            </tr>
          </thead>
          <tbody>
            {logs.map((log) => (
              <tr key={log.id}>
                <td>{new Date(log.createdAt).toLocaleString("sv-SE")}</td>
                <td>
                  <code>{log.actorUserId?.slice(0, 8) ?? "system"}</code>
                </td>
                <td>{log.actorType}</td>
                <td>
                  <code>{log.action}</code>
                </td>
                <td>{log.targetType ? `${log.targetType}:${log.targetId?.slice(0, 8)}` : "–"}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
