"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Loader2, RefreshCw } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Switch } from "@open-mercato/ui/primitives/switch";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
const normalizeStatusList = (list) => {
  if (list === null) return null;
  if (!Array.isArray(list)) return [];
  const set = /* @__PURE__ */ new Set();
  list.forEach((value) => {
    if (typeof value === "string" && value.trim().length) {
      set.add(value.trim());
    }
  });
  return Array.from(set);
};
const SAVE_CONTEXT_ID = "sales-order-editing-settings";
function OrderEditingSettings() {
  const t = useT();
  const scopeVersion = useOrganizationScopeVersion();
  const [loading, setLoading] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [options, setOptions] = React.useState([]);
  const [customerStatuses, setCustomerStatuses] = React.useState(null);
  const [addressStatuses, setAddressStatuses] = React.useState(null);
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: SAVE_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const translations = React.useMemo(
    () => ({
      title: t("sales.config.orderEditing.title", "Order editing guards"),
      description: t(
        "sales.config.orderEditing.description",
        "Control when customers and addresses can be changed on an order."
      ),
      customerLabel: t("sales.config.orderEditing.customerLabel", "Edit customer allowed at"),
      addressLabel: t("sales.config.orderEditing.addressLabel", "Edit addresses allowed at"),
      allowAny: t("sales.config.orderEditing.allowAny", "Allow at any status"),
      note: t(
        "sales.config.orderEditing.note",
        "Changing the customer clears assigned addresses to avoid mixing contact data."
      ),
      actions: {
        refresh: t("sales.config.orderEditing.actions.refresh", "Refresh"),
        refreshing: t("sales.config.orderEditing.actions.refreshing", "Refreshing\u2026"),
        save: t("sales.config.orderEditing.actions.save", "Save settings")
      },
      messages: {
        loadError: t("sales.config.orderEditing.errors.load", "Failed to load order editing settings."),
        saveError: t("sales.config.orderEditing.errors.save", "Failed to save order editing settings."),
        saved: t("sales.config.orderEditing.success.save", "Order editing settings saved.")
      }
    }),
    [t]
  );
  const loadSettings = React.useCallback(async () => {
    setLoading(true);
    try {
      const call = await apiCall("/api/sales/settings/order-editing");
      if (!call.ok) {
        flash(translations.messages.loadError, "error");
        return;
      }
      setOptions(Array.isArray(call.result?.orderStatuses) ? call.result.orderStatuses : []);
      setCustomerStatuses(normalizeStatusList(call.result?.orderCustomerEditableStatuses));
      setAddressStatuses(normalizeStatusList(call.result?.orderAddressEditableStatuses));
    } catch (err) {
      logger.error("sales.order-editing-settings.load failed", { err });
      flash(translations.messages.loadError, "error");
    } finally {
      setLoading(false);
    }
  }, [translations.messages.loadError]);
  React.useEffect(() => {
    void loadSettings();
  }, [loadSettings, scopeVersion]);
  const toggleAny = React.useCallback((kind) => {
    if (kind === "customer") {
      setCustomerStatuses((prev) => prev === null ? [] : null);
    } else {
      setAddressStatuses((prev) => prev === null ? [] : null);
    }
  }, []);
  const toggleStatus = React.useCallback((kind, value) => {
    const updater = kind === "customer" ? setCustomerStatuses : setAddressStatuses;
    updater((prev) => {
      const current = prev ?? [];
      if (current.includes(value)) {
        return current.filter((entry) => entry !== value);
      }
      return [...current, value];
    });
  }, []);
  const handleSubmit = React.useCallback(async () => {
    setSaving(true);
    try {
      const payload = {
        orderCustomerEditableStatuses: customerStatuses,
        orderAddressEditableStatuses: addressStatuses
      };
      const call = await runMutation({
        // optimistic-lock-exempt: single-row tenant order-editing settings blob — no per-record version / concurrent record edit
        operation: async () => {
          const response = await apiCall("/api/sales/settings/order-editing", {
            method: "PUT",
            headers: { "content-type": "application/json" },
            body: JSON.stringify(payload)
          });
          if (!response.ok) {
            throw new Error(translations.messages.saveError);
          }
          return response;
        },
        context: {
          formId: SAVE_CONTEXT_ID,
          resourceKind: "sales.settings",
          retryLastMutation
        },
        mutationPayload: payload
      });
      setCustomerStatuses(normalizeStatusList(call.result?.orderCustomerEditableStatuses));
      setAddressStatuses(normalizeStatusList(call.result?.orderAddressEditableStatuses));
      setOptions(Array.isArray(call.result?.orderStatuses) ? call.result.orderStatuses : []);
      flash(translations.messages.saved, "success");
    } catch (err) {
      logger.error("sales.order-editing-settings.save failed", { err });
      flash(translations.messages.saveError, "error");
    } finally {
      setSaving(false);
    }
  }, [addressStatuses, customerStatuses, retryLastMutation, runMutation, translations.messages.saveError, translations.messages.saved]);
  const renderStatusList = React.useCallback(
    (kind, values, label) => {
      const allowedAny = values === null;
      return /* @__PURE__ */ jsxs("div", { className: "space-y-3 rounded-none border bg-card/30 p-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: label }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: allowedAny ? t("sales.config.orderEditing.anyStatus", "Allowed at any status") : t("sales.config.orderEditing.pickStatuses", "Select statuses that allow this change") })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(Switch, { checked: allowedAny, onCheckedChange: () => toggleAny(kind), disabled: loading || saving }),
            /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: translations.allowAny })
          ] })
        ] }),
        !allowedAny && /* @__PURE__ */ jsx("div", { className: "grid gap-2 sm:grid-cols-2 lg:grid-cols-3", children: options.map((status) => {
          const checked = values?.includes(status.value) ?? false;
          return /* @__PURE__ */ jsxs(
            "label",
            {
              className: "flex items-center gap-2 rounded-none border bg-background p-2 text-sm",
              children: [
                /* @__PURE__ */ jsx(
                  "input",
                  {
                    type: "checkbox",
                    className: "h-4 w-4 rounded border",
                    checked,
                    onChange: () => toggleStatus(kind, status.value),
                    disabled: loading || saving
                  }
                ),
                /* @__PURE__ */ jsx("span", { className: "truncate", title: status.label || status.value, children: status.label || status.value }),
                /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "ml-auto text-overline uppercase tracking-wide", children: status.value })
              ]
            },
            status.id
          );
        }) })
      ] });
    },
    [loading, options, saving, t, toggleAny, toggleStatus, translations.allowAny]
  );
  return /* @__PURE__ */ jsxs("section", { className: "space-y-4 rounded-none border bg-card/30 p-5 shadow-sm !rounded-none", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: translations.title }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: translations.description })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex gap-2", children: /* @__PURE__ */ jsxs(
        Button,
        {
          variant: "ghost",
          size: "icon",
          type: "button",
          className: "rounded-none border-0 shadow-none hover:bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0",
          onClick: () => void loadSettings(),
          disabled: loading || saving,
          "aria-label": translations.actions.refresh,
          children: [
            loading ? /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4" }),
            /* @__PURE__ */ jsx("span", { className: "sr-only", children: loading ? translations.actions.refreshing : translations.actions.refresh })
          ]
        }
      ) })
    ] }),
    /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: translations.note }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
      renderStatusList("customer", customerStatuses, translations.customerLabel),
      renderStatusList("address", addressStatuses, translations.addressLabel)
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "icon",
          className: "rounded-none border-0 shadow-none hover:bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0",
          onClick: () => void loadSettings(),
          disabled: loading || saving,
          "aria-label": translations.actions.refresh,
          children: [
            loading ? /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4" }),
            /* @__PURE__ */ jsx("span", { className: "sr-only", children: loading ? translations.actions.refreshing : translations.actions.refresh })
          ]
        }
      ),
      /* @__PURE__ */ jsx(Button, { type: "button", onClick: () => void handleSubmit(), disabled: loading || saving, children: translations.actions.save })
    ] })
  ] });
}
export {
  OrderEditingSettings
};
//# sourceMappingURL=OrderEditingSettings.js.map
