"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import React from "react";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { Button } from "@open-mercato/ui/primitives/button";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { AuditLogsActions } from "../../components/AuditLogsActions.js";
import { AccessLogsTable } from "../../components/AccessLogsTable.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("audit_logs").child({ component: "audit-logs-page" });
const DEFAULT_PAGE_SIZE = 50;
function AuditLogsPage() {
  const t = useT();
  const [tab, setTab] = React.useState("actions");
  const [actions, setActions] = React.useState([]);
  const [accessLogs, setAccessLogs] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [undoableOnly, setUndoableOnly] = React.useState(false);
  const [actionsPage, setActionsPage] = React.useState(1);
  const [actionsPageSize, setActionsPageSize] = React.useState(DEFAULT_PAGE_SIZE);
  const [actionsTotal, setActionsTotal] = React.useState(0);
  const [actionsTotalPages, setActionsTotalPages] = React.useState(1);
  const actionsPageSizeRef = React.useRef(DEFAULT_PAGE_SIZE);
  const [accessPage, setAccessPage] = React.useState(1);
  const [accessPageSize, setAccessPageSize] = React.useState(DEFAULT_PAGE_SIZE);
  const [accessTotal, setAccessTotal] = React.useState(0);
  const [accessTotalPages, setAccessTotalPages] = React.useState(1);
  const accessPageSizeRef = React.useRef(DEFAULT_PAGE_SIZE);
  const fetchActions = React.useCallback(async (page, pageSize) => {
    const params = new URLSearchParams();
    params.set("page", String(page));
    params.set("pageSize", String(pageSize));
    if (undoableOnly) params.set("undoableOnly", "true");
    return readApiResultOrThrow(
      `/api/audit_logs/audit-logs/actions?${params.toString()}`,
      void 0,
      { errorMessage: t("audit_logs.error.load") }
    );
  }, [undoableOnly, t]);
  const fetchAccess = React.useCallback(async (page, pageSize) => {
    const params = new URLSearchParams();
    params.set("page", String(page));
    params.set("pageSize", String(pageSize));
    return readApiResultOrThrow(
      `/api/audit_logs/audit-logs/access?${params.toString()}`,
      void 0,
      { errorMessage: t("audit_logs.error.load") }
    );
  }, [t]);
  const loadAll = React.useCallback(async (actionPage, actionPageSize, accessPageNum, accessPageSizeNum) => {
    const [actionsRes, accessRes] = await Promise.all([
      fetchActions(actionPage, actionPageSize),
      fetchAccess(accessPageNum, accessPageSizeNum)
    ]);
    setActions(actionsRes.items ?? []);
    setActionsPage(actionsRes.page ?? actionPage);
    setActionsPageSize((prev) => {
      const resolved = actionsRes.pageSize ?? actionPageSize;
      actionsPageSizeRef.current = resolved;
      return resolved === prev ? prev : resolved;
    });
    setActionsTotal(actionsRes.total ?? (actionsRes.items?.length ?? 0));
    setActionsTotalPages(actionsRes.totalPages ?? 1);
    setAccessLogs(accessRes.items ?? []);
    const resolvedPage = accessRes.page ?? accessPageNum;
    const resolvedPageSize = accessRes.pageSize ?? accessPageSizeNum;
    const resolvedTotal = accessRes.total ?? (accessRes.items?.length ?? 0);
    const resolvedTotalPages = accessRes.totalPages ?? Math.max(1, Math.ceil((resolvedTotal || 0) / (resolvedPageSize || 1)));
    setAccessPage(resolvedPage);
    setAccessPageSize((prev) => {
      if (resolvedPageSize === prev) {
        accessPageSizeRef.current = prev;
        return prev;
      }
      accessPageSizeRef.current = resolvedPageSize;
      return resolvedPageSize;
    });
    setAccessTotal(resolvedTotal);
    setAccessTotalPages(resolvedTotalPages);
  }, [fetchActions, fetchAccess]);
  const loadWithState = React.useCallback(async (actionPage, actionPageSize, accessPageNum, accessPageSizeNum) => {
    setLoading(true);
    setError(null);
    try {
      await loadAll(actionPage, actionPageSize, accessPageNum, accessPageSizeNum);
    } catch (err) {
      logger.error("Failed to load audit logs", { err });
      setError(t("audit_logs.error.load"));
    } finally {
      setLoading(false);
    }
  }, [loadAll, t]);
  React.useEffect(() => {
    setActionsPage(1);
    setAccessPage(1);
    void loadWithState(1, actionsPageSizeRef.current, 1, accessPageSizeRef.current);
  }, [loadWithState, undoableOnly]);
  const renderRefreshButton = React.useCallback(() => /* @__PURE__ */ jsx(
    Button,
    {
      variant: "outline",
      size: "sm",
      onClick: () => void loadWithState(actionsPage, actionsPageSize, accessPage, accessPageSize),
      disabled: loading,
      children: loading ? t("audit_logs.common.refreshing") : t("audit_logs.common.refresh")
    }
  ), [loadWithState, actionsPage, actionsPageSize, accessPage, accessPageSize, loading, t]);
  const handleUndoError = React.useCallback(() => {
    setError(t("audit_logs.error.undo"));
  }, [t]);
  const handleRedoError = React.useCallback(() => {
    setError(t("audit_logs.error.redo"));
  }, [t]);
  const handleActionsPageChange = React.useCallback((nextPage) => {
    const totalPages = actionsTotalPages || 1;
    const normalized = Math.max(1, Math.min(nextPage, totalPages));
    void loadWithState(normalized, actionsPageSizeRef.current, accessPage, accessPageSizeRef.current);
  }, [actionsTotalPages, loadWithState, accessPage]);
  const handleAccessPageChange = React.useCallback((nextPage) => {
    const totalPages = accessTotalPages || 1;
    const normalized = Math.max(1, Math.min(nextPage, totalPages));
    void loadWithState(actionsPage, actionsPageSizeRef.current, normalized, accessPageSizeRef.current);
  }, [accessTotalPages, loadWithState, actionsPage]);
  const headerExtras = /* @__PURE__ */ jsxs(Fragment, { children: [
    renderRefreshButton(),
    /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 rounded border border-transparent px-2 py-1 text-sm text-muted-foreground", children: [
      /* @__PURE__ */ jsx("span", { children: t("audit_logs.filters.undoable_only") }),
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "checkbox",
          className: "h-4 w-4 rounded border border-input",
          checked: undoableOnly,
          onChange: (e) => setUndoableOnly(e.target.checked)
        }
      )
    ] })
  ] });
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { children: [
    /* @__PURE__ */ jsx("div", { className: "mb-6 border-b border-border", children: /* @__PURE__ */ jsxs("nav", { className: "flex items-center gap-6 text-sm", role: "tablist", "aria-label": t("audit_logs.tabs.label"), children: [
      /* @__PURE__ */ jsx(
        "button",
        {
          type: "button",
          role: "tab",
          "aria-selected": tab === "actions",
          className: `relative -mb-px border-b-2 px-0 pb-3 pt-2 font-medium transition-colors ${tab === "actions" ? "border-accent-indigo text-foreground" : "border-transparent text-muted-foreground hover:text-foreground"}`,
          onClick: () => setTab("actions"),
          children: t("audit_logs.actions.title")
        }
      ),
      /* @__PURE__ */ jsx(
        "button",
        {
          type: "button",
          role: "tab",
          "aria-selected": tab === "access",
          className: `relative -mb-px border-b-2 px-0 pb-3 pt-2 font-medium transition-colors ${tab === "access" ? "border-accent-indigo text-foreground" : "border-transparent text-muted-foreground hover:text-foreground"}`,
          onClick: () => setTab("access"),
          children: t("audit_logs.access.title")
        }
      )
    ] }) }),
    error && /* @__PURE__ */ jsx("div", { className: "mb-4 rounded-md border border-status-error-border bg-status-error-bg p-3 text-sm text-status-error-text", children: error }),
    tab === "actions" && /* @__PURE__ */ jsx(
      AuditLogsActions,
      {
        items: actions,
        onRefresh: () => loadWithState(actionsPage, actionsPageSize, accessPage, accessPageSize),
        isLoading: loading,
        headerExtras,
        onUndoError: handleUndoError,
        onRedoError: handleRedoError,
        pagination: {
          page: actionsPage,
          pageSize: actionsPageSize,
          total: actionsTotal,
          totalPages: actionsTotalPages,
          onPageChange: handleActionsPageChange
        }
      }
    ),
    tab === "access" && /* @__PURE__ */ jsx(
      AccessLogsTable,
      {
        items: accessLogs,
        isLoading: loading,
        actions: renderRefreshButton(),
        pagination: {
          page: accessPage,
          pageSize: accessPageSize,
          total: accessTotal,
          totalPages: accessTotalPages,
          onPageChange: handleAccessPageChange
        }
      }
    )
  ] }) });
}
export {
  AuditLogsPage as default
};
//# sourceMappingURL=page.js.map
