import React, { useState } from "react";
import PageHeader from "../../components/common/PageHeader.jsx";
import DataTable from "../../components/common/DataTable.jsx";
import ErrorBanner from "../../components/common/ErrorBanner.jsx";
import { listUsersLogs } from "../../services/usersApi.js";

export default function AdminActivityLogPage({ initialUserId = "" }) {
  const [logs, setLogs] = useState([]);
  const [userId, setUserId] = useState(initialUserId ? String(initialUserId) : "");
  const [error, setError] = useState("");

  const load = React.useCallback(async () => {
    try {
      setError("");
      const rows = await listUsersLogs(userId ? { user_id: userId } : {});
      setLogs(rows);
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    }
  }, [userId]);

  React.useEffect(() => {
    load();
  }, [load]);

  return (
    <div className="portal-page">
      <PageHeader
        title="Activity Log"
        subtitle="User audit history from users_logs (create, update, delete actions)."
        actions={<button type="button" className="swi-btn swi-btn--ghost" onClick={load}>Refresh</button>}
      />
      <ErrorBanner message={error} />
      <div className="ptw-panel">
        <div className="ptw-toolbar">
          <input
            className="swi-input"
            type="number"
            value={userId}
            onChange={(e) => setUserId(e.target.value)}
            placeholder="Filter by user id"
          />
          <button type="button" className="swi-btn swi-btn--ghost" onClick={load}>Apply</button>
          <button type="button" className="swi-btn swi-btn--ghost" onClick={() => setUserId("")}>Clear</button>
        </div>
        <DataTable
          columns={[
            { key: "log_id", label: "Log ID" },
            { key: "user_id", label: "User ID" },
            { key: "action", label: "Action" },
            { key: "employee_name", label: "Name" },
            { key: "created_at", label: "At" }
          ]}
          rows={logs}
          keyField="log_id"
        />
      </div>
    </div>
  );
}
