"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Loader2 } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Alert, AlertDescription, AlertTitle } from "../../primitives/alert.js";
import { Button } from "../../primitives/button.js";
import { Spinner } from "../../primitives/spinner.js";
import { useAiShortcuts } from "../useAiShortcuts.js";
import { cancelPendingAction } from "./pending-action-api.js";
import { useAiPendingActionPolling } from "./useAiPendingActionPolling.js";
import { MutationResultCard } from "./MutationResultCard.js";
function ConfirmationCard(props) {
  const t = useT();
  const pendingActionId = props.pendingActionId ?? "";
  const payload = props.payload ?? {};
  const injected = props.initialAction ?? payload.pendingAction ?? null;
  const { action, status, refresh } = useAiPendingActionPolling({
    pendingActionId,
    endpoint: props.endpoint,
    disabled: !pendingActionId
  });
  const effectiveAction = action ?? injected ?? null;
  const effectiveStatus = effectiveAction?.status ?? status;
  const [isCancelling, setIsCancelling] = React.useState(false);
  const [localError, setLocalError] = React.useState(
    payload.confirmError ? { code: payload.confirmError.code, message: payload.confirmError.message, extra: payload.confirmError.extra } : null
  );
  const canCancel = !isCancelling && (effectiveStatus === "pending" || effectiveStatus === "confirmed" || effectiveStatus == null);
  const handleCancel = React.useCallback(async () => {
    if (!canCancel) return;
    if (props.onCancel) {
      await props.onCancel();
      return;
    }
    if (!pendingActionId) return;
    setIsCancelling(true);
    try {
      const result = await cancelPendingAction(pendingActionId, {
        endpoint: props.endpoint
      });
      if (!result.ok) {
        setLocalError({
          code: result.error.code,
          message: result.error.message,
          extra: result.error.extra
        });
      }
      await refresh();
    } finally {
      setIsCancelling(false);
    }
  }, [canCancel, pendingActionId, props, refresh]);
  const { handleKeyDown } = useAiShortcuts({
    onCancel: () => {
      void handleCancel();
    },
    enabled: canCancel
  });
  const executionError = effectiveAction?.executionResult?.error;
  if (effectiveStatus === "confirmed" || effectiveStatus === "failed" || effectiveStatus === "cancelled" || effectiveStatus === "expired" || executionError) {
    return /* @__PURE__ */ jsx(
      MutationResultCard,
      {
        componentId: "mutation-result-card",
        pendingActionId,
        initialAction: effectiveAction ?? void 0,
        endpoint: props.endpoint
      }
    );
  }
  const summary = effectiveAction?.sideEffectsSummary ?? payload.sideEffectsSummary ?? t(
    "ai_assistant.chat.mutation_cards.confirmation.defaultSummary",
    "Applying the requested changes..."
  );
  return /* @__PURE__ */ jsxs(
    "section",
    {
      className: "rounded-md border border-border bg-muted/30 p-4 text-sm outline-none",
      tabIndex: 0,
      onKeyDown: handleKeyDown,
      "data-ai-confirmation-card": true,
      "data-ai-confirmation-status": effectiveStatus ?? "pending",
      "aria-busy": true,
      children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
          /* @__PURE__ */ jsx(Spinner, { size: "sm", className: "mt-0.5" }),
          /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsx("h4", { className: "text-sm font-semibold", children: t(
              "ai_assistant.chat.mutation_cards.confirmation.title",
              "Applying action..."
            ) }),
            /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-muted-foreground", children: summary })
          ] })
        ] }),
        localError ? /* @__PURE__ */ jsx(ConfirmationErrorAlert, { error: localError }) : null,
        /* @__PURE__ */ jsx("div", { className: "mt-3 flex items-center justify-end gap-2", children: /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            onClick: () => {
              void handleCancel();
            },
            disabled: !canCancel,
            "data-ai-confirmation-cancel": true,
            children: [
              isCancelling ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : null,
              /* @__PURE__ */ jsx("span", { children: t("ai_assistant.chat.mutation_cards.confirmation.cancel", "Cancel") })
            ]
          }
        ) })
      ]
    }
  );
}
function ConfirmationErrorAlert({
  error
}) {
  const t = useT();
  const code = error.code ?? "unknown";
  if (code === "stale_version") {
    const failedRecords = Array.isArray(error.extra?.failedRecords) ? error.extra?.failedRecords : [];
    return /* @__PURE__ */ jsxs(
      Alert,
      {
        variant: "warning",
        className: "mt-3",
        "data-ai-confirmation-error": "stale_version",
        children: [
          /* @__PURE__ */ jsx(AlertTitle, { children: t(
            "ai_assistant.chat.mutation_cards.confirmation.staleVersionTitle",
            "Re-propose required"
          ) }),
          /* @__PURE__ */ jsxs(AlertDescription, { children: [
            /* @__PURE__ */ jsx("p", { children: t(
              "ai_assistant.chat.mutation_cards.confirmation.staleVersionBody",
              "One or more records changed since this preview was generated. Ask the assistant to re-propose the change."
            ) }),
            failedRecords.length > 0 ? /* @__PURE__ */ jsx("ul", { className: "mt-2 list-disc pl-5 text-xs", children: failedRecords.map((record, idx) => /* @__PURE__ */ jsx(
              "li",
              {
                "data-ai-confirmation-stale-record": record.recordId ?? "",
                children: /* @__PURE__ */ jsx("span", { className: "font-mono", children: record.recordId ?? "\u2014" })
              },
              `${record.recordId ?? idx}`
            )) }) : null
          ] })
        ]
      }
    );
  }
  if (code === "schema_drift") {
    return /* @__PURE__ */ jsxs(
      Alert,
      {
        variant: "warning",
        className: "mt-3",
        "data-ai-confirmation-error": "schema_drift",
        children: [
          /* @__PURE__ */ jsx(AlertTitle, { children: t(
            "ai_assistant.chat.mutation_cards.confirmation.schemaDriftTitle",
            "Schema changed"
          ) }),
          /* @__PURE__ */ jsx(AlertDescription, { children: t(
            "ai_assistant.chat.mutation_cards.confirmation.schemaDriftBody",
            "The tool signature changed since this preview was generated. Ask the assistant to re-propose the change."
          ) })
        ]
      }
    );
  }
  if (code === "invalid_status") {
    return /* @__PURE__ */ jsxs(
      Alert,
      {
        variant: "warning",
        className: "mt-3",
        "data-ai-confirmation-error": "invalid_status",
        children: [
          /* @__PURE__ */ jsx(AlertTitle, { children: t(
            "ai_assistant.chat.mutation_cards.confirmation.invalidStatusTitle",
            "Action already resolved"
          ) }),
          /* @__PURE__ */ jsx(AlertDescription, { children: t(
            "ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody",
            "This action has already been confirmed, cancelled, or executed."
          ) })
        ]
      }
    );
  }
  return /* @__PURE__ */ jsxs(Alert, { variant: "destructive", className: "mt-3", "data-ai-confirmation-error": code, children: [
    /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.chat.mutation_cards.confirmation.errorTitle", "Confirm failed") }),
    /* @__PURE__ */ jsxs(AlertDescription, { children: [
      /* @__PURE__ */ jsx("span", { className: "mr-2 font-mono text-xs", children: code }),
      /* @__PURE__ */ jsx("span", { children: error.message })
    ] })
  ] });
}
var ConfirmationCard_default = ConfirmationCard;
export {
  ConfirmationCard,
  ConfirmationCard_default as default
};
//# sourceMappingURL=ConfirmationCard.js.map
