"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { ChevronDown, Eye, ShieldAlert } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "../../primitives/button.js";
import { useAiShortcuts } from "../useAiShortcuts.js";
import { confirmPendingAction, cancelPendingAction } from "./pending-action-api.js";
import { useAiPendingActionPolling } from "./useAiPendingActionPolling.js";
import { FieldDiffCard } from "./FieldDiffCard.js";
import { ConfirmationCard } from "./ConfirmationCard.js";
import { MutationResultCard } from "./MutationResultCard.js";
function summarizeBatch(records) {
  const labels = records.slice(0, 3).map((record) => record.label);
  return { count: records.length, labels };
}
function MutationPreviewCard(props) {
  const t = useT();
  const pendingActionId = props.pendingActionId ?? "";
  const payload = props.payload ?? {};
  const injected = props.initialAction ?? payload.pendingAction ?? null;
  const { action: polled, refresh } = useAiPendingActionPolling({
    pendingActionId,
    endpoint: props.endpoint,
    disabled: !pendingActionId
  });
  const action = polled ?? injected;
  const [expanded, setExpanded] = React.useState(false);
  const [phase, setPhase] = React.useState("preview");
  const [confirmError, setConfirmError] = React.useState(null);
  const handleConfirm = React.useCallback(async () => {
    if (!pendingActionId) return;
    if (phase !== "preview") return;
    setPhase("confirming");
    setConfirmError(null);
    const result = await confirmPendingAction(pendingActionId, {
      endpoint: props.endpoint
    });
    if (!result.ok) {
      setConfirmError(result.error);
      setPhase("preview");
      await refresh();
      return;
    }
    const handlerError = result.data?.mutationResult?.error;
    if (result.data?.ok === false || handlerError) {
      const mappedCode = typeof handlerError?.code === "string" && handlerError.code.length > 0 ? handlerError.code : "execution_failed";
      setConfirmError({
        status: 200,
        code: mappedCode,
        message: handlerError?.message ?? t(
          "ai_assistant.chat.mutation_cards.preview.handlerError",
          "The mutation handler reported an error. Review the details and re-propose if needed."
        )
      });
    }
    await refresh();
  }, [pendingActionId, phase, props.endpoint, refresh, t]);
  const handleCancel = React.useCallback(async () => {
    if (!pendingActionId) return;
    const result = await cancelPendingAction(pendingActionId, {
      endpoint: props.endpoint
    });
    if (!result.ok) {
      setConfirmError(result.error);
    }
    await refresh();
  }, [pendingActionId, props.endpoint, refresh]);
  const currentStatus = action?.status ?? null;
  const executionError = action?.executionResult?.error;
  const isTerminal = currentStatus === "confirmed" || currentStatus === "failed" || currentStatus === "cancelled" || currentStatus === "expired" || Boolean(executionError);
  const { handleKeyDown } = useAiShortcuts({
    onSubmit: () => {
      void handleConfirm();
    },
    onCancel: () => {
      void handleCancel();
    },
    enabled: phase === "preview" && !isTerminal
  });
  if (isTerminal && action) {
    return /* @__PURE__ */ jsx(
      MutationResultCard,
      {
        componentId: "mutation-result-card",
        pendingActionId,
        initialAction: action,
        endpoint: props.endpoint
      }
    );
  }
  if (phase === "confirming") {
    return /* @__PURE__ */ jsx(
      ConfirmationCard,
      {
        componentId: "confirmation-card",
        pendingActionId,
        initialAction: action ?? void 0,
        endpoint: props.endpoint,
        payload: {
          sideEffectsSummary: action?.sideEffectsSummary ?? null,
          pendingAction: action ?? void 0,
          confirmError: confirmError ?? void 0
        }
      }
    );
  }
  const batch = Array.isArray(action?.records) && action.records.length > 0 ? action.records : null;
  const summary = batch ? summarizeBatch(batch) : null;
  const hasReviewDetails = Boolean(batch);
  return /* @__PURE__ */ jsxs(
    "section",
    {
      className: "rounded-md border border-border bg-background p-4 text-sm outline-none",
      tabIndex: 0,
      onKeyDown: handleKeyDown,
      "data-ai-mutation-preview": true,
      "data-ai-mutation-preview-mode": batch ? "batch" : "single",
      children: [
        /* @__PURE__ */ jsx("header", { className: "flex items-start justify-between gap-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2", children: [
          /* @__PURE__ */ jsx(ShieldAlert, { className: "mt-0.5 size-4 text-status-warning-icon", "aria-hidden": true }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("h4", { className: "text-sm font-semibold", children: t(
              "ai_assistant.chat.mutation_cards.preview.title",
              "Review proposed changes"
            ) }),
            action?.sideEffectsSummary ? /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-muted-foreground", children: action.sideEffectsSummary }) : null
          ] })
        ] }) }),
        /* @__PURE__ */ jsx("div", { className: "mt-3", "data-ai-mutation-preview-body": true, children: summary ? /* @__PURE__ */ jsxs(
          "div",
          {
            className: "rounded-md border border-border bg-muted/30 p-3 text-sm",
            "data-ai-mutation-preview-batch-summary": true,
            children: [
              /* @__PURE__ */ jsxs("p", { className: "font-medium", children: [
                t(
                  "ai_assistant.chat.mutation_cards.preview.batchSummary",
                  "Batch update"
                ),
                ": ",
                /* @__PURE__ */ jsx("span", { "data-ai-mutation-preview-count": true, children: summary.count }),
                " ",
                /* @__PURE__ */ jsx("span", { children: t(
                  "ai_assistant.chat.mutation_cards.preview.batchRecords",
                  "records"
                ) })
              ] }),
              summary.labels.length > 0 ? /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs text-muted-foreground", children: [
                summary.labels.join(", "),
                summary.count > summary.labels.length ? ` +${summary.count - summary.labels.length}` : ""
              ] }) : null
            ]
          }
        ) : /* @__PURE__ */ jsx(FieldDiffCard, { fieldDiff: action?.fieldDiff ?? null }) }),
        expanded && hasReviewDetails ? /* @__PURE__ */ jsx("div", { className: "mt-3 rounded-md border border-border bg-muted/20 p-3", "data-ai-mutation-preview-details": true, children: /* @__PURE__ */ jsx(
          FieldDiffCard,
          {
            fieldDiff: action?.fieldDiff ?? null,
            records: action?.records ?? null
          }
        ) }) : null,
        /* @__PURE__ */ jsxs("div", { className: "mt-3 flex items-center justify-between gap-2", children: [
          hasReviewDetails ? /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => setExpanded((value) => !value),
              "data-ai-mutation-preview-review": true,
              children: [
                /* @__PURE__ */ jsx(Eye, { className: "size-4", "aria-hidden": true }),
                /* @__PURE__ */ jsx("span", { children: t(
                  "ai_assistant.chat.mutation_cards.preview.reviewDetails",
                  "Review details"
                ) }),
                /* @__PURE__ */ jsx(
                  ChevronDown,
                  {
                    className: `size-4 transition-transform ${expanded ? "rotate-180" : ""}`,
                    "aria-hidden": true
                  }
                )
              ]
            }
          ) : /* @__PURE__ */ jsx("span", { "aria-hidden": true }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: "outline",
                size: "sm",
                onClick: () => {
                  void handleCancel();
                },
                "data-ai-mutation-preview-cancel": true,
                children: t("ai_assistant.chat.mutation_cards.preview.cancel", "Cancel")
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                size: "sm",
                onClick: () => {
                  void handleConfirm();
                },
                "data-ai-mutation-preview-confirm": true,
                children: t("ai_assistant.chat.mutation_cards.preview.confirm", "Confirm")
              }
            )
          ] })
        ] })
      ]
    }
  );
}
var MutationPreviewCard_default = MutationPreviewCard;
export {
  MutationPreviewCard,
  MutationPreviewCard_default as default
};
//# sourceMappingURL=MutationPreviewCard.js.map
