"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { ChevronLeft, Clock, Loader2, RotateCcw, Undo2, X } from "lucide-react";
import { Button } from "../../primitives/button.js";
import { VersionHistoryDetail } from "./VersionHistoryDetail.js";
import { formatDate } from "@open-mercato/core/modules/audit_logs/lib/display-helpers";
import { apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { markRedoConsumed, markUndoSuccess } from "@open-mercato/ui/backend/operations/store";
import { getVersionHistoryActionLabel, getVersionHistoryStatusLabel } from "./labels.js";
import { useAuditPermissions, canUndoEntry, canRedoEntry } from "./useAuditPermissions.js";
import { Notice } from "@open-mercato/ui/primitives/Notice";
import { humanizeResourceKind } from "./labels.js";
function VersionHistoryPanel({
  open,
  onOpenChange,
  entries,
  isLoading,
  error,
  hasMore,
  onLoadMore,
  t,
  canUndoRedo,
  autoCheckAcl = true
}) {
  const shouldAutoCheck = canUndoRedo === void 0 && autoCheckAcl;
  const permissions = useAuditPermissions(shouldAutoCheck && open);
  const visibleEntries = React.useMemo(() => {
    if (canUndoRedo !== void 0 || !shouldAutoCheck) return entries;
    if (permissions.isLoading) return entries;
    if (permissions.canViewTenant) return entries;
    if (!permissions.currentUserId) return entries;
    return entries.filter((entry) => entry.actorUserId === permissions.currentUserId);
  }, [entries, canUndoRedo, shouldAutoCheck, permissions]);
  const [selectedEntry, setSelectedEntry] = React.useState(null);
  const [undoingToken, setUndoingToken] = React.useState(null);
  const [redoingId, setRedoingId] = React.useState(null);
  const latestUndoableId = React.useMemo(() => {
    const latest = visibleEntries.find((entry) => entry.undoToken && entry.executionState === "done");
    return latest?.id ?? null;
  }, [visibleEntries]);
  const latestUndoneId = React.useMemo(() => {
    const undone = visibleEntries.filter((entry) => entry.executionState === "undone");
    if (!undone.length) return null;
    const sorted = [...undone].sort((a, b) => {
      const aTs = Date.parse(a.updatedAt);
      const bTs = Date.parse(b.updatedAt);
      return (Number.isFinite(bTs) ? bTs : 0) - (Number.isFinite(aTs) ? aTs : 0);
    });
    return sorted[0]?.id ?? null;
  }, [visibleEntries]);
  React.useEffect(() => {
    if (!open) setSelectedEntry(null);
  }, [open]);
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);
  React.useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === "Escape" && open) {
        onOpenChange(false);
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [open, onOpenChange]);
  const handleUndo = React.useCallback(async (token) => {
    if (!token) return;
    setUndoingToken(token);
    try {
      await apiCallOrThrow("/api/audit_logs/audit-logs/actions/undo", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ undoToken: token })
      }, { errorMessage: t("audit_logs.error.undo") });
      markUndoSuccess(token);
      if (typeof window !== "undefined") {
        window.location.reload();
      }
    } catch (err) {
      console.error(t("audit_logs.actions.undo"), err);
    } finally {
      setUndoingToken(null);
    }
  }, [t]);
  const handleRedo = React.useCallback(async (logId) => {
    if (!logId) return;
    setRedoingId(logId);
    try {
      await apiCallOrThrow("/api/audit_logs/audit-logs/actions/redo", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ logId })
      }, { errorMessage: t("audit_logs.error.redo") });
      markRedoConsumed(logId);
      if (typeof window !== "undefined") {
        window.location.reload();
      }
    } catch (err) {
      console.error(t("audit_logs.actions.redo"), err);
    } finally {
      setRedoingId(null);
    }
  }, [t]);
  if (!open) return null;
  const isEmpty = visibleEntries.length === 0 && !isLoading && !error;
  const isInitialLoading = visibleEntries.length === 0 && isLoading;
  const isInitialError = visibleEntries.length === 0 && !!error;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        className: "fixed inset-0 z-40 bg-black/20",
        onClick: () => onOpenChange(false),
        "aria-hidden": "true"
      }
    ),
    /* @__PURE__ */ jsx(
      "div",
      {
        className: "fixed right-0 top-0 z-50 h-full w-full max-w-md border-l bg-background shadow-lg",
        role: "dialog",
        "aria-modal": "true",
        "aria-label": t("audit_logs.version_history.title"),
        children: /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b px-4 py-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              selectedEntry ? /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "icon",
                  onClick: () => setSelectedEntry(null),
                  "aria-label": t("audit_logs.version_history.detail.back"),
                  children: /* @__PURE__ */ jsx(ChevronLeft, { className: "h-5 w-5" })
                }
              ) : /* @__PURE__ */ jsx(Clock, { className: "h-5 w-5" }),
              /* @__PURE__ */ jsx("h2", { className: "font-semibold", children: selectedEntry ? t("audit_logs.version_history.detail.title") : t("audit_logs.version_history.title") })
            ] }),
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "icon",
                onClick: () => onOpenChange(false),
                "aria-label": t("audit_logs.version_history.close"),
                children: /* @__PURE__ */ jsx(X, { className: "h-5 w-5" })
              }
            )
          ] }),
          /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto px-4 py-4", children: selectedEntry ? /* @__PURE__ */ jsx(VersionHistoryDetail, { entry: selectedEntry, t }) : /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
            shouldAutoCheck && !permissions.isLoading && !permissions.canViewTenant && permissions.currentUserId ? /* @__PURE__ */ jsx(Notice, { compact: true, children: t("audit_logs.hint.view_self_only", "Showing only your own changes. Contact an administrator for broader access.") }) : null,
            isInitialLoading ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-muted-foreground", children: [
              /* @__PURE__ */ jsx(Loader2, { className: "mb-2 h-8 w-8 animate-spin" }),
              /* @__PURE__ */ jsx("p", { children: t("audit_logs.version_history.loading") })
            ] }) : null,
            isInitialError ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center gap-2 py-12 text-muted-foreground", children: [
              /* @__PURE__ */ jsx("p", { children: t("audit_logs.version_history.error") }),
              /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: onLoadMore, children: t("audit_logs.common.refresh") })
            ] }) : null,
            isEmpty ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-muted-foreground", children: [
              /* @__PURE__ */ jsx(Clock, { className: "mb-2 h-8 w-8 opacity-50" }),
              /* @__PURE__ */ jsx("p", { children: t("audit_logs.version_history.empty") })
            ] }) : null,
            visibleEntries.length > 0 ? /* @__PURE__ */ jsx("div", { className: "divide-y rounded-lg border", children: visibleEntries.map((entry) => {
              const statusLabel = getVersionHistoryStatusLabel(entry.executionState, t);
              const actionLabel = getVersionHistoryActionLabel(entry, t);
              const isRelatedEntry = entry.parentResourceKind != null;
              const entryCanUndo = canUndoRedo !== void 0 ? canUndoRedo : shouldAutoCheck ? canUndoEntry(permissions, entry.actorUserId) : true;
              const entryCanRedo = canUndoRedo !== void 0 ? canUndoRedo : shouldAutoCheck ? canRedoEntry(permissions, entry.actorUserId) : true;
              const canUndo = entryCanUndo && Boolean(entry.undoToken) && entry.executionState === "done" && entry.id === latestUndoableId;
              const showRedo = entryCanRedo && entry.executionState === "undone";
              const canRedo = showRedo && entry.id === latestUndoneId;
              return /* @__PURE__ */ jsxs(
                "div",
                {
                  className: `flex items-start justify-between gap-3 py-3 transition-colors hover:bg-muted/40 ${isRelatedEntry ? "pl-8 pr-4 border-l-2 border-l-muted-foreground/20" : "px-4"}`,
                  children: [
                    /* @__PURE__ */ jsxs(
                      Button,
                      {
                        type: "button",
                        variant: "ghost",
                        className: "h-auto min-w-0 flex-1 flex-col items-start justify-start gap-1 whitespace-normal px-0 py-0 text-left hover:bg-transparent",
                        onClick: () => setSelectedEntry(entry),
                        children: [
                          isRelatedEntry ? /* @__PURE__ */ jsx("span", { className: "text-[10px] uppercase tracking-wider text-muted-foreground/70 font-medium", children: humanizeResourceKind(entry.resourceKind, t) }) : null,
                          /* @__PURE__ */ jsx("div", { className: "break-words text-sm font-medium", children: actionLabel }),
                          /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-x-2 text-xs text-muted-foreground", children: [
                            /* @__PURE__ */ jsx("span", { children: entry.actorUserName || entry.actorUserId || t("audit_logs.common.none") }),
                            /* @__PURE__ */ jsx("span", { children: "\u2022" }),
                            /* @__PURE__ */ jsx("span", { children: formatDate(entry.createdAt) }),
                            /* @__PURE__ */ jsx("span", { children: "\u2022" }),
                            /* @__PURE__ */ jsx("span", { children: statusLabel })
                          ] })
                        ]
                      }
                    ),
                    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 pt-1", children: [
                      canUndo ? /* @__PURE__ */ jsxs(
                        Button,
                        {
                          variant: "ghost",
                          size: "sm",
                          className: "h-8 gap-1 px-2 text-xs",
                          "aria-label": t("audit_logs.actions.undo"),
                          onClick: (event) => {
                            event.stopPropagation();
                            void handleUndo(entry.undoToken);
                          },
                          disabled: undoingToken === entry.undoToken || Boolean(redoingId),
                          children: [
                            /* @__PURE__ */ jsx(Undo2, { className: "size-4", "aria-hidden": "true" }),
                            /* @__PURE__ */ jsx("span", { children: t("audit_logs.actions.undo") })
                          ]
                        }
                      ) : null,
                      showRedo ? /* @__PURE__ */ jsxs(
                        Button,
                        {
                          variant: "ghost",
                          size: "sm",
                          className: "h-8 gap-1 px-2 text-xs",
                          "aria-label": t("audit_logs.actions.redo"),
                          onClick: (event) => {
                            event.stopPropagation();
                            void handleRedo(entry.id);
                          },
                          disabled: !canRedo || redoingId === entry.id || Boolean(undoingToken),
                          children: [
                            /* @__PURE__ */ jsx(RotateCcw, { className: "size-4", "aria-hidden": "true" }),
                            /* @__PURE__ */ jsx("span", { children: t("audit_logs.actions.redo") })
                          ]
                        }
                      ) : null
                    ] })
                  ]
                },
                entry.id
              );
            }) }) : null,
            error && visibleEntries.length > 0 ? /* @__PURE__ */ jsx("div", { className: "text-xs text-red-500", children: error }) : null,
            hasMore ? /* @__PURE__ */ jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxs(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: onLoadMore,
                disabled: isLoading,
                children: [
                  isLoading ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }) : null,
                  t("audit_logs.version_history.load_more")
                ]
              }
            ) }) : null
          ] }) })
        ] })
      }
    )
  ] });
}
export {
  VersionHistoryPanel
};
//# sourceMappingURL=VersionHistoryPanel.js.map
