"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 { Input } from "@open-mercato/ui/primitives/input";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  DOCUMENT_NUMBER_TOKENS,
  DEFAULT_ORDER_NUMBER_FORMAT,
  DEFAULT_QUOTE_NUMBER_FORMAT
} from "../lib/documentNumberTokens.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
const DEFAULT_STATE = {
  orderNumberFormat: DEFAULT_ORDER_NUMBER_FORMAT,
  quoteNumberFormat: DEFAULT_QUOTE_NUMBER_FORMAT,
  orderNextNumber: "1",
  quoteNextNumber: "1"
};
const normalizeState = (payload) => ({
  orderNumberFormat: typeof payload?.orderNumberFormat === "string" && payload.orderNumberFormat.trim().length ? payload.orderNumberFormat : DEFAULT_ORDER_NUMBER_FORMAT,
  quoteNumberFormat: typeof payload?.quoteNumberFormat === "string" && payload.quoteNumberFormat.trim().length ? payload.quoteNumberFormat : DEFAULT_QUOTE_NUMBER_FORMAT,
  orderNextNumber: typeof payload?.nextOrderNumber === "number" && Number.isFinite(payload.nextOrderNumber) ? String(payload.nextOrderNumber) : "1",
  quoteNextNumber: typeof payload?.nextQuoteNumber === "number" && Number.isFinite(payload.nextQuoteNumber) ? String(payload.nextQuoteNumber) : "1"
});
const SAVE_CONTEXT_ID = "sales-document-number-settings";
function DocumentNumberSettings() {
  const t = useT();
  const scopeVersion = useOrganizationScopeVersion();
  const [formState, setFormState] = React.useState(DEFAULT_STATE);
  const [loading, setLoading] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [tokens, setTokens] = React.useState(DOCUMENT_NUMBER_TOKENS);
  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.numbering.title", "Document numbers"),
    description: t(
      "sales.config.numbering.description",
      "Control how sales orders and quotes are numbered. Formats can include dates, sequences, and random fragments."
    ),
    orderLabel: t("sales.config.numbering.orderFormat", "Order number format"),
    quoteLabel: t("sales.config.numbering.quoteFormat", "Quote number format"),
    orderNext: t("sales.config.numbering.orderNext", "Next order sequence"),
    quoteNext: t("sales.config.numbering.quoteNext", "Next quote sequence"),
    save: t("sales.config.numbering.actions.save", "Save settings"),
    reset: t("sales.config.numbering.actions.reset", "Reset changes"),
    refresh: t("sales.config.numbering.actions.refresh", "Refresh"),
    refreshing: t("sales.config.numbering.actions.refreshing", "Refreshing\u2026"),
    tokensTitle: t("sales.config.numbering.tokensTitle", "Available tokens"),
    tokensHint: t(
      "sales.config.numbering.tokensHint",
      "Combine tokens to shape your identifiers, e.g. ORDER/{yyyy}/{seq:5}."
    ),
    errors: {
      load: t("sales.config.numbering.errors.load", "Failed to load numbering settings."),
      save: t("sales.config.numbering.errors.save", "Failed to save numbering settings.")
    },
    messages: {
      saved: t("sales.config.numbering.messages.saved", "Numbering settings saved.")
    }
  }), [t]);
  const handleLoad = React.useCallback(async () => {
    setLoading(true);
    try {
      const call = await apiCall("/api/sales/settings/document-numbers");
      if (call.ok) {
        setFormState(normalizeState(call.result));
        setTokens(Array.isArray(call.result?.tokens) && call.result.tokens.length ? call.result.tokens : DOCUMENT_NUMBER_TOKENS);
      } else {
        flash(translations.errors.load, "error");
      }
    } catch (err) {
      logger.error("sales.document-number-settings.load failed", { err });
      flash(translations.errors.load, "error");
    } finally {
      setLoading(false);
    }
  }, [translations.errors.load]);
  React.useEffect(() => {
    void handleLoad();
  }, [handleLoad, scopeVersion]);
  const handleChange = (key) => (event) => {
    setFormState((prev) => ({ ...prev, [key]: event.target.value }));
  };
  const handleSubmit = React.useCallback(async (event) => {
    event.preventDefault();
    setSaving(true);
    try {
      const payload = {
        orderNumberFormat: formState.orderNumberFormat.trim(),
        quoteNumberFormat: formState.quoteNumberFormat.trim(),
        orderNextNumber: Number.parseInt(formState.orderNextNumber, 10) || void 0,
        quoteNextNumber: Number.parseInt(formState.quoteNextNumber, 10) || void 0
      };
      const call = await runMutation({
        // optimistic-lock-exempt: single-row tenant numbering settings blob — no per-record version / concurrent record edit
        operation: async () => {
          const response = await apiCall("/api/sales/settings/document-numbers", {
            method: "PUT",
            headers: { "content-type": "application/json" },
            body: JSON.stringify(payload)
          });
          if (!response.ok) {
            throw new Error(translations.errors.save);
          }
          return response;
        },
        context: {
          formId: SAVE_CONTEXT_ID,
          resourceKind: "sales.settings",
          retryLastMutation
        },
        mutationPayload: payload
      });
      setFormState(normalizeState(call.result));
      setTokens(Array.isArray(call.result?.tokens) && call.result.tokens.length ? call.result.tokens : DOCUMENT_NUMBER_TOKENS);
      flash(translations.messages.saved, "success");
    } catch (err) {
      logger.error("sales.document-number-settings.save failed", { err });
      flash(translations.errors.save, "error");
    } finally {
      setSaving(false);
    }
  }, [formState.orderNextNumber, formState.orderNumberFormat, formState.quoteNextNumber, formState.quoteNumberFormat, retryLastMutation, runMutation, translations.errors.save, translations.messages.saved]);
  const handleReset = React.useCallback(() => {
    setFormState(DEFAULT_STATE);
    void handleLoad();
  }, [handleLoad]);
  return /* @__PURE__ */ jsxs("section", { className: "rounded-none border bg-card/30 p-5 shadow-sm", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between", 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: handleLoad,
          disabled: loading || saving,
          "aria-label": translations.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.refreshing : translations.refresh })
          ]
        }
      ) })
    ] }),
    /* @__PURE__ */ jsxs("form", { className: "mt-4 space-y-5", onSubmit: handleSubmit, children: [
      /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2", children: [
        /* @__PURE__ */ jsxs("label", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx("div", { className: "text-sm font-medium", children: translations.orderLabel }),
          /* @__PURE__ */ jsx(
            Input,
            {
              value: formState.orderNumberFormat,
              onChange: handleChange("orderNumberFormat"),
              disabled: loading || saving,
              spellCheck: false
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("sales.config.numbering.orderHint", "Example: ORDER/{yyyy}/{seq:5}") })
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx("div", { className: "text-sm font-medium", children: translations.quoteLabel }),
          /* @__PURE__ */ jsx(
            Input,
            {
              value: formState.quoteNumberFormat,
              onChange: handleChange("quoteNumberFormat"),
              disabled: loading || saving,
              spellCheck: false
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("sales.config.numbering.quoteHint", "Example: QUOTE/{yy}/{mm}/{seq:4}") })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2", children: [
        /* @__PURE__ */ jsxs("label", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx("div", { className: "text-sm font-medium", children: translations.orderNext }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "number",
              min: 1,
              value: formState.orderNextNumber,
              onChange: handleChange("orderNextNumber"),
              disabled: loading || saving
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("sales.config.numbering.sequenceHint", "Applied on the next generated number for this type.") })
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx("div", { className: "text-sm font-medium", children: translations.quoteNext }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "number",
              min: 1,
              value: formState.quoteNextNumber,
              onChange: handleChange("quoteNextNumber"),
              disabled: loading || saving
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("sales.config.numbering.sequenceHintQuote", "Resets the quote counter for the next document.") })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2 rounded-lg border bg-muted/50 p-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm font-medium", children: [
          translations.tokensTitle,
          /* @__PURE__ */ jsx("span", { className: "text-xs font-normal text-muted-foreground", children: translations.tokensHint })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: tokens.map((entry) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 rounded border bg-background px-2 py-1", children: [
          /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "font-mono text-xs", children: entry.token }),
          /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: entry.description })
        ] }, entry.token)) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2", children: [
        /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: handleReset, disabled: loading || saving, children: translations.reset }),
        /* @__PURE__ */ jsx(Button, { type: "submit", disabled: saving, children: saving ? t("sales.config.numbering.actions.saving", "Saving\u2026") : translations.save })
      ] })
    ] })
  ] });
}
export {
  DocumentNumberSettings
};
//# sourceMappingURL=DocumentNumberSettings.js.map
