"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@open-mercato/ui/primitives/dialog";
import { useDialogKeyHandler } from "@open-mercato/ui/hooks/useDialogKeyHandler";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { updateCrud } from "@open-mercato/ui/backend/utils/crud";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { E } from "../../../../generated/entities.ids.generated.js";
import { handleSectionMutationError } from "./optimisticLock.js";
function toDateInputValue(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return date.toISOString().slice(0, 10);
}
function ReturnEditDialog({
  open,
  returnRecord,
  orderId,
  organizationId,
  tenantId,
  onClose,
  onSaved
}) {
  const t = useT();
  const dialogContentRef = React.useRef(null);
  const initialValues = React.useMemo(
    () => ({
      id: returnRecord?.id ?? "",
      // Drives CrudForm's automatic optimistic-lock header derivation.
      updatedAt: returnRecord?.updatedAt ?? null,
      reason: returnRecord?.reason ?? "",
      notes: returnRecord?.notes ?? "",
      returnedAt: toDateInputValue(returnRecord?.returnedAt)
    }),
    [returnRecord]
  );
  const fields = React.useMemo(
    () => [
      {
        id: "reason",
        label: t("sales.returns.reason", "Reason"),
        type: "text",
        placeholder: t("sales.returns.reason.placeholder", "Optional")
      },
      {
        id: "returnedAt",
        label: t("sales.returns.returnedAt", "Returned at"),
        type: "date",
        maxDate: /* @__PURE__ */ new Date()
      },
      {
        id: "notes",
        label: t("sales.returns.notes", "Notes"),
        type: "textarea",
        placeholder: t("sales.returns.notes.placeholder", "Optional")
      }
    ],
    [t]
  );
  const handleSubmit = React.useCallback(
    async (values) => {
      if (!returnRecord) return;
      const reason = typeof values.reason === "string" ? values.reason.trim() : "";
      const notes = typeof values.notes === "string" ? values.notes.trim() : "";
      const returnedAt = typeof values.returnedAt === "string" ? values.returnedAt.trim() : "";
      try {
        const result = await updateCrud(
          "sales/returns",
          {
            id: returnRecord.id,
            orderId,
            ...organizationId ? { organizationId } : {},
            ...tenantId ? { tenantId } : {},
            reason,
            notes,
            ...returnedAt ? { returnedAt } : {}
          },
          {
            errorMessage: t("sales.returns.errors.update", "Failed to update return.")
          }
        );
        if (result.ok) {
          flash(t("sales.returns.updated", "Return updated."), "success");
          onClose();
          await onSaved();
        }
      } catch (err) {
        if (handleSectionMutationError(err, t, () => void onSaved())) {
          onClose();
          return;
        }
        throw err;
      }
    },
    [onClose, onSaved, orderId, organizationId, returnRecord, t, tenantId]
  );
  const handleSubmitForm = React.useCallback(
    () => dialogContentRef.current?.querySelector("form")?.requestSubmit(),
    []
  );
  const handleKeyDown = useDialogKeyHandler({
    onConfirm: handleSubmitForm,
    onCancel: onClose
  });
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: (next) => !next ? onClose() : void 0, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-2xl", onKeyDown: handleKeyDown, ref: dialogContentRef, children: [
    /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("sales.returns.edit.title", "Edit return") }) }),
    /* @__PURE__ */ jsx(
      CrudForm,
      {
        embedded: true,
        fields,
        entityId: E.sales.sales_return,
        initialValues,
        submitLabel: t("sales.returns.edit.submit", "Save changes"),
        onSubmit: handleSubmit
      }
    )
  ] }) });
}
export {
  ReturnEditDialog
};
//# sourceMappingURL=ReturnEditDialog.js.map
