"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Input } from "@open-mercato/ui/primitives/input";
import { Label } from "@open-mercato/ui/primitives/label";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { AppearanceSelector } from "@open-mercato/core/modules/dictionaries/components/AppearanceSelector";
import { renderDictionaryColor, renderDictionaryIcon } from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
const DEFAULT_FORM = {
  value: "",
  label: "",
  color: null,
  icon: null
};
const PAGE_SIZE = 100;
const normalizeEntry = (raw) => {
  if (!raw || typeof raw !== "object") return null;
  const value = typeof raw.value === "string" ? raw.value.trim() : "";
  const id = typeof raw.id === "string" ? raw.id : "";
  if (!value || !id) return null;
  const label = typeof raw.label === "string" && raw.label.trim().length ? raw.label.trim() : value;
  const color = typeof raw.color === "string" && /^#([0-9a-fA-F]{6})$/.test(raw.color) ? `#${raw.color.slice(1).toLowerCase()}` : null;
  const icon = typeof raw.icon === "string" && raw.icon.trim().length ? raw.icon.trim() : null;
  return {
    id,
    value,
    label,
    color,
    icon,
    createdAt: typeof raw.createdAt === "string" ? raw.createdAt : null,
    updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : null
  };
};
const SAVE_CONTEXT_ID = "sales-adjustment-kind-settings";
function AdjustmentKindSettings() {
  const t = useT();
  const scopeVersion = useOrganizationScopeVersion();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: SAVE_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const mutationContext = React.useMemo(
    () => ({
      formId: SAVE_CONTEXT_ID,
      resourceKind: "sales.adjustmentKinds",
      retryLastMutation
    }),
    [retryLastMutation]
  );
  const [items, setItems] = React.useState([]);
  const [search, setSearch] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [dialog, setDialog] = React.useState(null);
  const [form, setForm] = React.useState(DEFAULT_FORM);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const labels = React.useMemo(
    () => ({
      title: t("sales.config.adjustmentKinds.title", "Adjustment kinds"),
      description: t(
        "sales.config.adjustmentKinds.description",
        "Manage reusable adjustment kinds for taxes, surcharges, shipping, and discounts."
      ),
      add: t("sales.config.adjustmentKinds.actions.add", "Add adjustment kind"),
      refresh: t("sales.config.adjustmentKinds.actions.refresh", "Refresh"),
      edit: t("sales.config.adjustmentKinds.actions.edit", "Edit"),
      delete: t("sales.config.adjustmentKinds.actions.delete", "Delete"),
      deleteConfirm: t("sales.config.adjustmentKinds.confirm.delete", 'Delete adjustment kind "{{code}}"?'),
      createTitle: t("sales.config.adjustmentKinds.dialog.createTitle", "Create adjustment kind"),
      editTitle: t("sales.config.adjustmentKinds.dialog.editTitle", "Edit adjustment kind"),
      createDescription: t(
        "sales.config.adjustmentKinds.dialog.createDescription",
        "Define a reusable adjustment kind shown in document adjustment dialogs."
      ),
      editDescription: t(
        "sales.config.adjustmentKinds.dialog.editDescription",
        "Update the code, label, or appearance for this adjustment kind."
      ),
      codeLabel: t("sales.config.adjustmentKinds.form.codeLabel", "Code"),
      codePlaceholder: t("sales.config.adjustmentKinds.form.codePlaceholder", "e.g. discount"),
      labelLabel: t("sales.config.adjustmentKinds.form.labelLabel", "Label"),
      labelPlaceholder: t("sales.config.adjustmentKinds.form.labelPlaceholder", "e.g. Discount"),
      appearanceLabel: t("sales.config.adjustmentKinds.form.appearanceLabel", "Appearance"),
      saveCreate: t("sales.config.adjustmentKinds.actions.create", "Create"),
      saveEdit: t("sales.config.adjustmentKinds.actions.save", "Save changes"),
      cancel: t("ui.actions.cancel", "Cancel"),
      required: t("sales.config.adjustmentKinds.errors.required", "Code is required."),
      loadError: t("sales.config.adjustmentKinds.errors.load", "Failed to load adjustment kinds."),
      saveError: t("sales.config.adjustmentKinds.errors.save", "Failed to save adjustment kind."),
      deleteError: t("sales.config.adjustmentKinds.errors.delete", "Failed to delete adjustment kind."),
      created: t("sales.config.adjustmentKinds.messages.created", "Adjustment kind created."),
      updated: t("sales.config.adjustmentKinds.messages.updated", "Adjustment kind updated."),
      deleted: t("sales.config.adjustmentKinds.messages.deleted", "Adjustment kind deleted."),
      empty: t("sales.config.adjustmentKinds.table.empty", "No adjustment kinds yet."),
      searchPlaceholder: t("sales.config.adjustmentKinds.search.placeholder", "Search by code or label\u2026"),
      columns: {
        code: t("sales.config.adjustmentKinds.table.code", "Code"),
        label: t("sales.config.adjustmentKinds.table.label", "Label"),
        appearance: t("sales.config.adjustmentKinds.table.appearance", "Appearance")
      },
      appearanceLabels: {
        colorLabel: t("dictionaries.form.colorLabel", "Color"),
        colorHelp: t("dictionaries.form.colorHelp", "Pick a highlight color."),
        colorClearLabel: t("dictionaries.form.colorClear", "Remove color"),
        iconLabel: t("dictionaries.form.iconLabel", "Icon or emoji"),
        iconPlaceholder: t("dictionaries.form.iconPlaceholder", "Type an emoji or icon token."),
        iconPickerTriggerLabel: t("dictionaries.form.iconPickerTriggerLabel", "Browse icons and emoji"),
        iconSearchPlaceholder: t("dictionaries.form.iconSearchPlaceholder", "Search icons or emojis\u2026"),
        iconSearchEmptyLabel: t("dictionaries.form.iconSearchEmptyLabel", "No icons match your search."),
        iconSuggestionsLabel: t("dictionaries.form.iconSuggestionsLabel", "Suggestions"),
        iconClearLabel: t("dictionaries.form.iconClearLabel", "Remove icon"),
        previewEmptyLabel: t("dictionaries.form.previewEmptyLabel", "No appearance selected")
      }
    }),
    [t]
  );
  const loadItems = React.useCallback(async () => {
    setLoading(true);
    try {
      const payload = await readApiResultOrThrow(
        `/api/sales/adjustment-kinds?pageSize=${PAGE_SIZE}`,
        void 0,
        { errorMessage: labels.loadError }
      );
      const mapped = Array.isArray(payload.items) ? payload.items.map((entry) => normalizeEntry(entry)).filter((entry) => Boolean(entry)) : [];
      setItems(mapped);
    } catch (err) {
      logger.error("sales.adjustment-kinds.list failed", { err });
      flash(labels.loadError, "error");
    } finally {
      setLoading(false);
    }
  }, [labels.loadError]);
  React.useEffect(() => {
    loadItems().catch(() => {
    });
  }, [loadItems, scopeVersion]);
  const openDialog = React.useCallback((state) => {
    if (state.mode === "edit") {
      setForm({
        value: state.entry.value,
        label: state.entry.label,
        color: state.entry.color,
        icon: state.entry.icon
      });
    } else {
      setForm(DEFAULT_FORM);
    }
    setError(null);
    setDialog(state);
  }, []);
  const closeDialog = React.useCallback(() => {
    setDialog(null);
    setSubmitting(false);
    setError(null);
    setForm(DEFAULT_FORM);
  }, []);
  const handleSubmit = React.useCallback(async () => {
    if (!dialog) return;
    const trimmedValue = form.value.trim();
    const trimmedLabel = form.label.trim();
    if (!trimmedValue) {
      setError(labels.required);
      return;
    }
    setSubmitting(true);
    setError(null);
    try {
      const payload = {
        value: trimmedValue
      };
      if (trimmedLabel) payload.label = trimmedLabel;
      if (form.color !== void 0) payload.color = form.color;
      if (form.icon !== void 0) payload.icon = form.icon;
      const method = dialog.mode === "create" ? "POST" : "PUT";
      const body = dialog.mode === "create" ? JSON.stringify(payload) : JSON.stringify({ id: dialog.entry.id, ...payload });
      const lockHeader = dialog.mode === "edit" ? buildOptimisticLockHeader(dialog.entry.updatedAt) : {};
      await runMutation({
        operation: async () => {
          const call = await withScopedApiRequestHeaders(
            lockHeader,
            () => apiCall("/api/sales/adjustment-kinds", {
              method,
              headers: { "content-type": "application/json" },
              body
            })
          );
          if (!call.ok) {
            await raiseCrudError(call.response, labels.saveError);
          }
          return call;
        },
        context: mutationContext,
        mutationPayload: dialog.mode === "create" ? { action: "create", ...payload } : { action: "update", id: dialog.entry.id, ...payload }
      });
      flash(dialog.mode === "create" ? labels.created : labels.updated, "success");
      closeDialog();
      await loadItems();
    } catch (err) {
      logger.error("sales.adjustment-kinds.save failed", { err });
      const message = err instanceof Error ? err.message : labels.saveError;
      setError(message);
    } finally {
      setSubmitting(false);
    }
  }, [closeDialog, dialog, form.color, form.icon, form.label, form.value, labels, loadItems, mutationContext, runMutation]);
  const handleDelete = React.useCallback(
    async (entry) => {
      const message = labels.deleteConfirm.replace("{{code}}", entry.label || entry.value);
      const confirmed = await confirm({
        title: message,
        variant: "destructive"
      });
      if (!confirmed) return;
      try {
        await runMutation({
          operation: async () => {
            const call = await withScopedApiRequestHeaders(
              buildOptimisticLockHeader(entry.updatedAt),
              () => apiCall("/api/sales/adjustment-kinds", {
                method: "DELETE",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({ id: entry.id })
              })
            );
            if (!call.ok) {
              await raiseCrudError(call.response, labels.deleteError);
            }
            return call;
          },
          context: mutationContext,
          mutationPayload: { action: "delete", id: entry.id }
        });
        flash(labels.deleted, "success");
        await loadItems();
      } catch (err) {
        logger.error("sales.adjustment-kinds.delete failed", { err });
        const message2 = err instanceof Error ? err.message : labels.deleteError;
        flash(message2, "error");
      }
    },
    [confirm, labels, loadItems, mutationContext, runMutation]
  );
  const formKeyHandler = React.useCallback(
    (event) => {
      if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
        event.preventDefault();
        void handleSubmit();
      }
    },
    [handleSubmit]
  );
  const columns = React.useMemo(() => [
    {
      accessorKey: "value",
      header: labels.columns.code,
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "font-mono uppercase", children: row.original.value })
    },
    {
      accessorKey: "label",
      header: labels.columns.label,
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "font-medium", children: row.original.label })
    },
    {
      id: "appearance",
      header: labels.columns.appearance,
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        renderDictionaryIcon(row.original.icon, "h-4 w-4"),
        renderDictionaryColor(row.original.color, "h-4 w-4 rounded-full")
      ] })
    }
  ], [labels.columns.appearance, labels.columns.code, labels.columns.label]);
  const filteredItems = React.useMemo(() => {
    const term = search.trim().toLowerCase();
    if (!term) return items;
    return items.filter((item) => item.value.toLowerCase().includes(term) || item.label.toLowerCase().includes(term));
  }, [items, search]);
  const onRowClick = React.useCallback((entry) => {
    openDialog({ mode: "edit", entry });
  }, [openDialog]);
  return /* @__PURE__ */ jsxs("section", { className: "border bg-card text-card-foreground shadow-sm", id: "adjustment-kinds", children: [
    /* @__PURE__ */ jsxs("div", { className: "border-b px-6 py-4 space-y-1", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: labels.title }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: labels.description })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "px-2 py-4 sm:px-4", children: /* @__PURE__ */ jsx(
      DataTable,
      {
        data: filteredItems,
        columns,
        embedded: true,
        isLoading: loading,
        searchValue: search,
        onSearchChange: setSearch,
        searchPlaceholder: labels.searchPlaceholder,
        emptyState: /* @__PURE__ */ jsx("p", { className: "py-8 text-center text-sm text-muted-foreground", children: labels.empty }),
        actions: /* @__PURE__ */ jsx(Button, { size: "sm", onClick: () => openDialog({ mode: "create" }), children: labels.add }),
        refreshButton: {
          label: labels.refresh,
          onRefresh: () => {
            void loadItems();
          },
          isRefreshing: loading
        },
        rowActions: (entry) => /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              { id: "edit", label: labels.edit, onSelect: () => openDialog({ mode: "edit", entry }) },
              { id: "delete", label: labels.delete, destructive: true, onSelect: () => {
                void handleDelete(entry);
              } }
            ]
          }
        ),
        onRowClick
      }
    ) }),
    /* @__PURE__ */ jsx(Dialog, { open: dialog !== null, onOpenChange: (open) => {
      if (!open) closeDialog();
    }, children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: dialog?.mode === "edit" ? labels.editTitle : labels.createTitle }),
        /* @__PURE__ */ jsx(DialogDescription, { children: dialog?.mode === "edit" ? labels.editDescription : labels.createDescription })
      ] }),
      /* @__PURE__ */ jsxs(
        "form",
        {
          className: "space-y-4",
          onKeyDown: formKeyHandler,
          onSubmit: (event) => {
            event.preventDefault();
            void handleSubmit();
          },
          children: [
            /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "adjustment-kind-code", children: labels.codeLabel }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "adjustment-kind-code",
                  value: form.value,
                  onChange: (event) => setForm((prev) => ({ ...prev, value: event.target.value })),
                  placeholder: labels.codePlaceholder,
                  className: "font-mono uppercase",
                  disabled: dialog?.mode === "edit"
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "adjustment-kind-label", children: labels.labelLabel }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "adjustment-kind-label",
                  value: form.label,
                  onChange: (event) => setForm((prev) => ({ ...prev, label: event.target.value })),
                  placeholder: labels.labelPlaceholder
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsx(Label, { children: labels.appearanceLabel }),
              /* @__PURE__ */ jsx(
                AppearanceSelector,
                {
                  color: form.color,
                  icon: form.icon,
                  onColorChange: (next) => setForm((prev) => ({ ...prev, color: next })),
                  onIconChange: (next) => setForm((prev) => ({ ...prev, icon: next })),
                  labels: labels.appearanceLabels
                }
              )
            ] }),
            error ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: error }) : null
          ]
        }
      ),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: closeDialog, children: labels.cancel }),
        /* @__PURE__ */ jsx(Button, { onClick: () => void handleSubmit(), disabled: submitting, children: dialog?.mode === "edit" ? labels.saveEdit : labels.saveCreate })
      ] })
    ] }) }),
    ConfirmDialogElement
  ] });
}
export {
  AdjustmentKindSettings
};
//# sourceMappingURL=AdjustmentKindSettings.js.map
