import { ref as A, computed as G, h as C, defineComponent as j, watch as re, resolveComponent as R, openBlock as F, createElementBlock as B, createVNode as b, unref as i, createElementVNode as c, toDisplayString as $, createBlock as M, withCtx as T, Fragment as pe, renderList as ve, createTextVNode as ye, createCommentVNode as se, isRef as ge, normalizeClass as _e, normalizeStyle as be, createSlots as ke, Teleport as xe, normalizeProps as he, guardReactiveProps as we } from "vue";
import { a as P, c as L, i as oe, u as Re } from "./app-Bpb4394e.js";
import { useDialog as Ie, useSnackbar as Y, components as U, useProxiedModel as Se, useBreakpoints as Fe } from "@feedmepos/ui-library";
import { F as S } from "./form-mode.enum-BKiNVH6A.js";
import { useI18n as z, useCoreStore as Ge } from "@feedmepos/mf-common";
import { defineStore as ue, storeToRefs as ae } from "pinia";
import { D as ie, R as K } from "./row-action.enum-DQ9bJ_uv.js";
import { c as Ve } from "./component-kqxARxvM.js";
import { u as Ce, _ as De } from "./SingleColumnLayout.vue_vue_type_script_setup_true_lang-sUxHOj47.js";
import { _ as Ae, F as le } from "./TableActionableRow.vue_vue_type_script_setup_true_lang-Ca_eYa8-.js";
import { _ as $e } from "./FmInventoryTableToolbar.vue_vue_type_script_setup_true_lang-j3aDZ2cT.js";
import { d as de } from "./defineDeepModel-BF0Cvhza.js";
import { I as Te, A as Ee, U as Me, R as ce } from "./rules-CoimOM7X.js";
import { L as Ue, P as Be, D as Le } from "./app-DiX-EfV6.js";
import { u as Pe } from "./FmMultiselectDialog-DHiMw0t6.js";
import { r as me } from "./random-CSbEbElR.js";
import { u as ze, R as Ne } from "./usePromise-CbVUCxhj.js";
const H = ue(
  "ingredientGroupactions",
  function() {
    const _ = Ie(), f = Y(), k = P(), { t: l } = z(), v = A();
    function e() {
      const u = {
        modelValue: {},
        mode: S.CREATE,
        show: !0,
        "onUpdate:show"(m) {
          v.value.show = m;
        }
      };
      v.value = u;
    }
    async function a(u) {
      const m = {
        modelValue: L(u),
        mode: S.UPDATE,
        show: !0,
        "onUpdate:show"(r) {
          v.value.show = r;
        }
      };
      v.value = m;
    }
    async function t(u, m, r) {
      m.value = !0;
      try {
        await k.deleteSkuGroup(u), f.open({
          title: "Success",
          message: `Deleted ${u.name}`,
          type: "success"
        });
      } catch (y) {
        f.open({
          title: `Cannot delete ${u.name}`,
          message: "Please try again.",
          type: "error"
        }), console.error("failed to delete ingredient", y);
      } finally {
        m.value = !1, r();
      }
    }
    function n(u, m, r) {
      _.open({
        title: l("inventory.ingredient.delete.title", [(u == null ? void 0 : u.name) ?? ""]),
        closeButton: !1,
        message: l("inventory.ingredient.delete.message"),
        primaryActions: {
          text: l("common.delete"),
          close: !0,
          variant: "destructive"
        },
        secondaryActions: {
          text: l("common.cancel"),
          close: !0
        }
      }).onPrimary(() => t(u, m, r));
    }
    function s() {
    }
    function g() {
    }
    return {
      createIngredientGroup: e,
      updateIngredientGroup: a,
      deleteIngredientGroup: n,
      importIngredientGroups: s,
      exportIngredientGroups: g,
      ingredientGroupDialogProps: v
    };
  }
), Oe = ue(
  "ingredientGroupTable",
  function() {
    const _ = A(!1), f = Y(), k = P(), l = H();
    async function v() {
      _.value = !0;
      try {
        await k.readInventory();
      } catch (t) {
        console.error("error on reading inventory", t), f.open({
          title: "Error",
          message: "Something went wrong, please try again.",
          type: "error"
        });
      } finally {
        _.value = !1;
      }
    }
    function e(t, n) {
      switch (n = L(n), t) {
        case K.Edit:
          return l.updateIngredientGroup(n);
        case K.Delete:
          return l.deleteIngredientGroup(
            n,
            _,
            () => v()
          );
      }
    }
    const a = G(() => [
      {
        accessorKey: "name",
        header: () => "Name"
      },
      {
        accessorKey: "skuRefs.length",
        header: () => "No. of items"
      },
      {
        accessorKey: "ref",
        header: () => "Reference"
      },
      {
        id: "action",
        header: "",
        cell(t) {
          return Ve(
            [ie[K.Edit], ie[K.Delete]],
            (n) => {
              e(n, t.row.original);
            }
          );
        },
        enableSorting: !1,
        size: 40,
        meta: {
          cellClass: "",
          headerClass: ""
        }
      }
    ]);
    return {
      fetchIngredientGroups: v,
      loading: _,
      columnDefs: a
    };
  }
);
function qe(o) {
  return {
    addItem: () => {
      const l = o.create();
      o.items = [...o.items, l];
    },
    updateItem: (l) => {
      l && (o.items = o.items.map(
        (v) => o.id(v) === o.id(l) ? l : v
      ));
    },
    removeItem: (l) => {
      o.items = o.items.filter((v) => o.id(v) !== o.id(l));
    }
  };
}
function fe(o) {
  const _ = Pe(), f = P(), k = G(() => [
    {
      id: "delete",
      header: "",
      cell(e) {
        const a = e.row.original;
        return C(
          "div",
          { class: "w-full flex justify-end" },
          C(U.FmButton, {
            class: "delete-button",
            key: a._id,
            type: "button",
            icon: "delete",
            variant: "tertiary",
            size: "md",
            disabled: o.disabled ?? !1,
            onClick: () => {
              o.skuRefs = o.skuRefs.filter((t) => t._id !== a._id);
            }
          })
        );
      },
      enableSorting: !1,
      size: 40,
      meta: {
        cellClass: "",
        headerClass: ""
      }
    },
    {
      id: "skuRef",
      header: () => "Ingredient",
      accessorFn: (e) => {
        var a, t;
        return `${((a = f.skuById[e._id]) == null ? void 0 : a.name) ?? ""} (${((t = f.skuById[e._id]) == null ? void 0 : t.code) ?? ""})`;
      },
      cell: ({ row: e }) => {
        const a = f.skuById[e.original._id];
        return C(
          "div",
          {
            class: "w-full flex flex-col"
          },
          [
            C("div", { class: "fm-typo-en-body-lg-400 line-clamp-1" }, a.name),
            C(
              "div",
              { class: "fm-typo-en-body-md-400 line-clamp-1 text-fm-color-typo-secondary" },
              a.code
            )
          ]
        );
      },
      size: "auto",
      enableSorting: !1
    },
    {
      id: "unit",
      header: () => "Unit",
      accessorFn: (e) => {
        const a = f.skuById[e._id];
        return a.unit.measurements.computeFirst(
          (t) => t.id === e.trackingMeasurement ? t.name : null
        ) ?? a.unit.name;
      },
      enableSorting: !1
    },
    {
      id: "unitOption",
      header: () => "Unit",
      accessorKey: "trackingMeasurement",
      cell(e) {
        const a = f.skuById[e.row.original._id];
        if (!a) return null;
        const t = [
          {
            label: a.unit.name,
            sublabel: a.unit.abbrev,
            value: null
          },
          ...a.unit.measurements.map((n) => ({
            label: n.name,
            sublabel: n.abbrev,
            value: n.id
          }))
        ].filter((n) => !n.label.toLowerCase().includes("inactive"));
        return C(U.FmSelect, {
          modelValue: e.row.original.trackingMeasurement ?? null,
          items: t,
          disabled: o.disabled ?? !1,
          "onUpdate:modelValue": (n) => {
            o.skuRefs = o.skuRefs.map((s) => s._id === e.row.original._id ? { ...s, trackingMeasurement: n } : s);
          }
        });
      },
      enableSorting: !1
    },
    {
      id: "priority",
      header: () => "Priority",
      accessorKey: "priority",
      enableSorting: !0,
      cell(e) {
        const a = e.row.original;
        return C(U.FmTextField, {
          modelValue: a.priority ?? e.row.index + 1,
          rules: [
            Te(),
            Ee(1),
            Me(
              o.skuRefs.filter((t) => t._id !== a._id).map((t) => {
                const n = f.skuById[t._id];
                return {
                  label: n == null ? void 0 : n.name,
                  value: t.priority
                };
              })
            )
          ],
          "onUpdate:modelValue": (t) => {
            const n = Number(t);
            isNaN(n) || (o.skuRefs = o.skuRefs.map((s) => s._id === e.row.original._id ? { ...s, priority: n } : s));
          }
        });
      }
    },
    {
      id: "default",
      header: () => "",
      accessorKey: "default",
      cell(e) {
        const a = f.skuById[e.row.original._id];
        return a ? C(U.FmCheckbox, {
          modelValue: e.row.original.default ?? !1,
          value: a._id,
          disabled: o.disabled ?? !1,
          "onUpdate:modelValue": () => {
            o.skuRefs = o.skuRefs.map((t) => t._id === e.row.original._id ? { ...t, default: !0 } : { ...t, default: !1 });
          }
        }) : null;
      },
      enableSorting: !1,
      size: 40,
      meta: {
        cellClass: "",
        headerClass: ""
      }
    },
    {
      id: "move",
      header: "",
      cell(e) {
        const a = e.row.original;
        return C("div", { class: "w-full flex justify-end" }, [
          C(U.FmButton, {
            key: a._id,
            type: "button",
            icon: "keyboard_arrow_up",
            variant: "tertiary",
            size: "md",
            disabled: o.disabled ?? !1,
            onClick: () => {
              const t = [...o.skuRefs], n = t.findIndex((s) => s._id === a._id);
              if (n > 0) {
                const s = t[n - 1];
                t[n - 1] = a, t[n] = s;
              }
              o.skuRefs = [...t];
            }
          }),
          C(U.FmButton, {
            key: a._id,
            type: "button",
            icon: "keyboard_arrow_down",
            variant: "tertiary",
            size: "md",
            disabled: o.disabled ?? !1,
            onClick: () => {
              const t = [...o.skuRefs], n = t.findIndex((s) => s._id === a._id);
              if (n < t.length - 1) {
                const s = t[n + 1];
                t[n + 1] = a, t[n] = s;
              }
              o.skuRefs = [...t];
            }
          })
        ]);
      },
      enableSorting: !1,
      size: 40,
      meta: {
        cellClass: "",
        headerClass: ""
      }
    }
  ]);
  return {
    get columnDefs() {
      return k.value;
    },
    promptAddIngredient: async () => {
      if (!o.isDefaultList && !o.allowOverride)
        return _.alert("Not allowed", "You cannot add ingredients to this list.");
      const v = f.skus.map((t) => ({
        label: t.name,
        sublabel: t.code,
        value: t._id
      })), e = (o.skuRefs ?? []).map((t) => t._id), a = await _.multiSelect(v, e, (t) => {
        var s, g, u, m, r, y;
        const n = (s = o.skuRefs) == null ? void 0 : s.findIndex((w) => w._id === t);
        return {
          _id: t,
          trackingMeasurement: typeof n != "number" || n == -1 ? (g = f.skuById[t]) == null ? void 0 : g.trackingMeasurement : (m = (u = o.skuRefs) == null ? void 0 : u[n]) == null ? void 0 : m.trackingMeasurement,
          priority: ((y = (r = o.skuRefs) == null ? void 0 : r[n]) == null ? void 0 : y.priority) ?? o.skuRefs.length,
          default: !1
        };
      });
      o.skuRefs = a ?? o.skuRefs;
    },
    columnVisibility: {
      delete: o.isDefaultList || !!o.allowOverride,
      unit: !o.isDefaultList && !o.allowOverride,
      unitOption: o.isDefaultList || !!o.allowOverride,
      // previous demo: sort priority by moving sku element in the array,
      // new demo: sort priority using priority field.
      // can reenable if this use case is requested to be restored
      move: !1
    }
  };
}
const Ke = { class: "flex flex-col gap-16" }, je = { class: "flex flex-col" }, He = { class: "flex flex-col gap-4" }, Ye = { class: "flex flex-col gap-16" }, Je = { class: "flex flex-col" }, Qe = { class: "flex flex-col gap-4" }, We = { class: "flex-1 fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Xe = /* @__PURE__ */ j({
  __name: "IngredientGroupRuleField",
  props: {
    disabled: { type: Boolean },
    modelValue: {}
  },
  setup(o) {
    const _ = o, { t: f } = z(), k = Ge(), l = G(() => {
      var g;
      const n = /* @__PURE__ */ new Map(), s = k.restaurants.value.map((u) => u.customAttributes ?? {});
      for (const u of s)
        for (const [m, r] of Object.entries(u))
          n.has(m) || n.set(m, /* @__PURE__ */ new Set()), r && ((g = n.get(m)) == null || g.add(r));
      return n;
    }), v = G(() => [
      ...[...l.value.entries()].map(([s, g]) => ({
        type: "string",
        key: s,
        entity: "restaurant",
        values: [...g]
      }))
    ]), e = de("modelValue", {
      get default() {
        return {
          _id: `skuGroupRule_${(/* @__PURE__ */ new Date()).toISOString()}_${me(4)}`,
          name: "",
          rule: null,
          skuRefs: []
        };
      },
      watchProps: !0
    }), a = A(e.rule ? Ue.build(e.rule) : null);
    re(
      a,
      (n) => {
        e.rule = n ? Be.build(n) : null;
      },
      { deep: !0, immediate: !0 }
    );
    const t = fe({
      get disabled() {
        return _.disabled ?? !1;
      },
      get skuRefs() {
        return e.skuRefs ?? [];
      },
      set skuRefs(n) {
        e.skuRefs = n;
      },
      isDefaultList: !1,
      allowOverride: !1
    });
    return (n, s) => {
      const g = R("FmTextField"), u = R("FmLabel"), m = R("FmFormGroup"), r = R("FmTable");
      return F(), B("div", Ke, [
        b(g, {
          modelValue: i(e).name,
          "onUpdate:modelValue": s[0] || (s[0] = (y) => i(e).name = y),
          label: i(f)("inventory.ingredientGroup.form.rules.name"),
          "label-mark": "required",
          rules: [i(ce)()]
        }, null, 8, ["modelValue", "label", "rules"]),
        c("div", je, [
          c("div", He, [
            b(u, {
              label: i(f)("inventory.ingredientGroup.form.rules.title"),
              required: ""
            }, null, 8, ["label"]),
            b(i(Le), {
              modelValue: a.value,
              "onUpdate:modelValue": s[1] || (s[1] = (y) => a.value = y),
              attributes: v.value
            }, null, 8, ["modelValue", "attributes"])
          ]),
          b(m, {
            "model-value": a.value,
            rules: [
              (y) => {
                var w;
                return !!((w = y == null ? void 0 : y.rules) != null && w.length) || "At least one rule is required";
              }
            ]
          }, null, 8, ["model-value", "rules"])
        ]),
        c("div", Ye, [
          c("div", Je, [
            c("div", Qe, [
              c("div", null, [
                b(u, {
                  label: i(f)("inventory.ingredientGroup.form.rules.ingredients"),
                  required: ""
                }, null, 8, ["label"])
              ])
            ]),
            b(m, {
              "model-value": i(e).skuRefs,
              rules: [
                (y) => !!(y != null && y.length) || "At least one ingredient is required"
              ]
            }, null, 8, ["model-value", "rules"])
          ]),
          b(r, {
            "row-data": i(e).skuRefs,
            "column-defs": i(t).columnDefs,
            "page-size": i(e).skuRefs.length,
            "shrink-at": 9999,
            "column-visibility": i(t).columnVisibility,
            "hide-footer": ""
          }, null, 8, ["row-data", "column-defs", "page-size", "column-visibility"])
        ]),
        c("div", We, $(i(f)("inventory.ingredientGroup.form.defaultRule.defaultCheckbox")), 1)
      ]);
    };
  }
}), Ze = { class: "flex flex-col gap-16" }, et = { class: "flex flex-col gap-16" }, tt = { class: "flex flex-col" }, nt = { class: "flex items-center" }, st = { class: "flex-1" }, ot = { class: "flex flex-col gap-8" }, at = { class: "flex-1 fm-typo-en-title-sm-600" }, it = { class: "flex-1 fm-typo-en-body-md-400 text-fm-color-typo-secondary px-4" }, lt = { class: "flex flex-col gap-16" }, rt = { class: "flex flex-col gap-8" }, ut = { class: "flex-1 fm-typo-en-title-sm-600" }, dt = { class: "flex-1 fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, ct = { class: "flex flex-col gap-12" }, mt = { class: "flex items-center" }, ft = { class: "flex-1 fm-typo-en-body-lg-600 line-clamp-1" }, pt = { key: 0 }, vt = {
  key: 1,
  class: "fm-typo-en-body-lg-400"
}, yt = /* @__PURE__ */ j({
  __name: "IngredientGroupForm",
  props: {
    mode: {},
    disabled: { type: Boolean },
    modelValue: {},
    menu: {}
  },
  emits: ["validation-success"],
  setup(o, { expose: _, emit: f }) {
    const k = o, l = de("modelValue", {
      watchProps: !0
    }), v = f, { t: e } = z(), a = qe({
      get items() {
        return l.rules ?? [];
      },
      set items(s) {
        l.rules = s;
      },
      create: function() {
        var s;
        return {
          _id: `skuGroupRule_${(/* @__PURE__ */ new Date()).toISOString()}_${me(4)}`,
          name: "",
          rule: null,
          skuRefs: ((s = k.modelValue) == null ? void 0 : s.defaultSkuRefs) ?? []
        };
      },
      id: function(s) {
        return s._id;
      }
    }), t = fe({
      get disabled() {
        return k.disabled;
      },
      get skuRefs() {
        return l.defaultSkuRefs ?? [];
      },
      set skuRefs(s) {
        l.defaultSkuRefs = s;
        const g = s.map((r) => r._id), u = l.rules;
        if (!u) return;
        const m = s.groupBy(
          (r) => r._id,
          (r) => r.trackingMeasurement
        );
        for (const r of u) {
          const y = r.skuRefs.filter((x) => g.includes(x._id)), w = s.filter(
            (x) => !y.some((I) => I._id === x._id)
          );
          r.skuRefs = [...y, ...w].map((x) => {
            var I;
            return {
              ...x,
              trackingMeasurement: ((I = m.get(x._id)) == null ? void 0 : I[0]) ?? null
            };
          });
        }
        l.rules = [...u];
      },
      isDefaultList: !0
    }), n = A();
    return _({
      validateInputs: () => {
        var s;
        return (s = n.value) == null ? void 0 : s.validateInputs();
      },
      resetInputsValidation: () => {
        var s;
        return (s = n.value) == null ? void 0 : s.resetInputsValidation();
      },
      resetInputs: () => {
        var s;
        return (s = n.value) == null ? void 0 : s.resetInputs();
      }
    }), (s, g) => {
      const u = R("FmTextField"), m = R("FmButton"), r = R("FmFormGroup"), y = R("FmTable"), w = R("FmCard"), x = R("FmForm");
      return F(), M(x, {
        onValidationSuccess: g[2] || (g[2] = (I) => v("validation-success")),
        ref_key: "formRef",
        ref: n,
        class: "flex flex-col gap-64"
      }, {
        default: T(() => {
          var I;
          return [
            c("div", Ze, [
              b(u, {
                label: i(e)("inventory.ingredientGroup.form.name"),
                "label-mark": "required",
                rules: [i(ce)()],
                modelValue: i(l).name,
                "onUpdate:modelValue": g[0] || (g[0] = (d) => i(l).name = d)
              }, null, 8, ["label", "rules", "modelValue"]),
              b(u, {
                label: i(e)("inventory.ingredientGroup.form.ref"),
                "label-mark": "optional",
                modelValue: i(l).ref,
                "onUpdate:modelValue": g[1] || (g[1] = (d) => i(l).ref = d)
              }, null, 8, ["label", "modelValue"])
            ]),
            c("div", et, [
              c("div", tt, [
                c("div", nt, [
                  c("div", st, [
                    c("div", ot, [
                      c("div", at, $(i(e)("inventory.ingredientGroup.form.defaultRule.title")), 1)
                    ])
                  ]),
                  c("div", null, [
                    b(m, {
                      disabled: s.disabled,
                      label: "Add ingredient",
                      "prepend-icon": "link",
                      variant: "plain",
                      class: "border-1 rounded-lg border-fm-color-primary",
                      onClick: i(t).promptAddIngredient,
                      size: "md"
                    }, null, 8, ["disabled", "onClick"])
                  ])
                ]),
                b(r, {
                  "model-value": i(l).defaultSkuRefs,
                  rules: [
                    (d) => !!(d != null && d.length) || "At least one ingredient is required"
                  ]
                }, null, 8, ["model-value", "rules"])
              ]),
              c("div", null, [
                b(y, {
                  "row-data": i(l).defaultSkuRefs ?? [],
                  "column-defs": i(t).columnDefs,
                  "column-visibility": i(t).columnVisibility,
                  "page-size": (I = i(l).defaultSkuRefs) == null ? void 0 : I.length,
                  "shrink-at": 9999,
                  "hide-footer": ""
                }, null, 8, ["row-data", "column-defs", "column-visibility", "page-size"])
              ]),
              c("div", it, $(i(e)("inventory.ingredientGroup.form.defaultRule.defaultCheckbox")), 1)
            ]),
            c("div", lt, [
              c("div", rt, [
                c("div", ut, $(i(e)("inventory.ingredientGroup.form.rules.title")), 1),
                c("div", dt, $(i(e)("inventory.ingredientGroup.form.rules.description")), 1)
              ]),
              (F(!0), B(pe, null, ve(i(l).rules, (d, p) => (F(), M(w, {
                key: d.id,
                variant: "outlined",
                class: "p-16"
              }, {
                default: T(() => [
                  c("div", ct, [
                    c("div", mt, [
                      c("div", ft, [
                        ye($(i(e)("inventory.ingredientGroup.form.rules.rule_N", [p + 1])), 1),
                        d.name ? (F(), B("span", pt, ": ")) : se("", !0),
                        d.name ? (F(), B("span", vt, $(d.name), 1)) : se("", !0)
                      ]),
                      b(m, {
                        variant: "tertiary",
                        icon: "delete",
                        onClick: (h) => i(a).removeItem(d)
                      }, null, 8, ["onClick"])
                    ]),
                    c("div", null, [
                      (F(), M(Xe, {
                        key: d._id,
                        "model-value": d,
                        "onUpdate:modelValue": i(a).updateItem,
                        disabled: s.disabled,
                        menu: s.menu
                      }, null, 8, ["model-value", "onUpdate:modelValue", "disabled", "menu"]))
                    ])
                  ])
                ]),
                _: 2
              }, 1024))), 128)),
              c("div", null, [
                b(m, {
                  variant: "plain",
                  icon: "add",
                  label: i(e)("inventory.ingredientGroup.form.rules.addRule"),
                  onClick: i(a).addItem
                }, null, 8, ["label", "onClick"])
              ])
            ])
          ];
        }),
        _: 1
      }, 512);
    };
  }
}), gt = {
  key: 0,
  class: "text-fm-color-typo-primary fm-typo-en-body-lg-400"
}, _t = { class: "flex gap-4" }, bt = /* @__PURE__ */ j({
  __name: "IngredientGroupDialog",
  props: {
    show: { type: Boolean },
    mode: { default: S.READ },
    modelValue: {}
  },
  emits: ["update:show"],
  setup(o) {
    const _ = o, f = P(), k = ze(() => f.readCachedMenu()), l = G(
      () => k.result.value.state === Ne.success ? k.result.value.data : void 0
    ), v = Y(), { t: e } = z(), a = Se(_, "show");
    function t() {
      return {
        _id: "",
        name: "",
        rules: []
      };
    }
    const n = A(t()), s = A(`${Math.random()}`);
    re(
      () => _.show,
      (d) => {
        if (!d) return;
        let p = L(_.modelValue ?? t());
        p.defaultSkuRefs && (p.defaultSkuRefs = p.defaultSkuRefs.map((h, V) => ({
          ...h,
          priority: h.priority ?? V + 1
        })));
        for (let h = 0; p.rules && h < p.rules.length; h++) {
          const V = p.rules[h];
          V.skuRefs = V.skuRefs.map((D, E) => ({
            ...D,
            priority: D.priority ?? E + 1
          }));
        }
        n.value = p, s.value = p._id || `${Math.random()}`;
      }
    );
    const g = G(() => {
      switch (_.mode) {
        case S.READ:
          return "";
        case S.UPDATE:
          return e("inventory.ingredientGroup.update.title");
        case S.CREATE:
          return e("inventory.ingredientGroup.create.title");
      }
      return "";
    }), u = G(() => {
      switch (_.mode) {
        case S.READ:
          return "";
        case S.UPDATE:
          return e("common.save");
        case S.CREATE:
          return e("common.add");
      }
      return "";
    }), m = A(), r = A(!1);
    async function y() {
      r.value = !0;
      const d = L(n.value);
      try {
        await f.createSkuGroup(d), a.value = !1, v.open({
          title: e("inventory.common.success"),
          message: e("inventory.ingredientGroup.create.success", { name: d.name }),
          type: "success"
        });
      } catch (p) {
        p instanceof oe || v.open({
          title: e("inventory.ingredientGroup.create.error.title"),
          message: e("inventory.ingredientGroup.create.error.message"),
          type: "error"
        });
      } finally {
        r.value = !1;
      }
    }
    async function w() {
      r.value = !0;
      const d = L(n.value);
      try {
        await f.updateSkuGroup(d), r.value = !1, a.value = !1, v.open({
          title: e("inventory.common.success"),
          message: e("inventory.ingredientGroup.update.success", { name: d.name }),
          type: "success"
        });
      } catch (p) {
        p instanceof oe || v.open({
          title: e("inventory.ingredientGroup.update.error.title"),
          message: e("inventory.ingredientGroup.update.error.message"),
          type: "error"
        });
      } finally {
        r.value = !1;
      }
    }
    function x() {
      var d, p;
      (p = (d = m.value) == null ? void 0 : d.validateInputs) == null || p.call(d);
    }
    function I() {
      switch (_.mode) {
        case S.READ:
          return;
        case S.UPDATE:
          return w();
        case S.CREATE:
          return y();
      }
    }
    return (d, p) => {
      const h = R("FmButton"), V = R("FmSideSheet");
      return F(), M(V, {
        "model-value": i(a),
        "onUpdate:modelValue": p[3] || (p[3] = (D) => ge(a) ? a.value = D : null),
        header: g.value,
        "close-button": "",
        "dismiss-away": "",
        "max-width": 800
      }, {
        "side-sheet-footer": T(() => [
          c("div", _t, [
            b(h, {
              loading: r.value,
              label: u.value,
              onClick: x
            }, null, 8, ["loading", "label"]),
            b(h, {
              disabled: r.value,
              label: i(e)("common.close"),
              variant: "tertiary",
              onClick: p[2] || (p[2] = (D) => a.value = !1)
            }, null, 8, ["disabled", "label"])
          ])
        ]),
        default: T(() => [
          l.value ? (F(), M(yt, {
            menu: l.value,
            class: "w-full",
            ref_key: "hasValidationExpose",
            ref: m,
            key: s.value,
            "model-value": n.value,
            "onUpdate:modelValue": p[0] || (p[0] = (D) => n.value = D),
            mode: d.mode,
            disabled: r.value,
            onValidationSuccess: p[1] || (p[1] = (D) => I())
          }, null, 8, ["menu", "model-value", "mode", "disabled"])) : (F(), B("div", gt, "Loading.."))
        ]),
        _: 1
      }, 8, ["model-value", "header"]);
    };
  }
}), kt = { class: "flex flex-col py-8" }, xt = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, ht = { class: "fm-typo-en-body-lg-600 text-fm-color-typo-primary" }, Pt = /* @__PURE__ */ j({
  __name: "IngredientGroupView",
  setup(o) {
    const _ = P(), f = G(() => _.skuGroups), k = Re(), { t: l } = z(), {
      createIngredientGroup: v,
      updateIngredientGroup: e,
      importIngredientGroups: a,
      exportIngredientGroups: t
    } = H(), { columnDefs: n, loading: s } = ae(Oe()), { ingredientGroupDialogProps: g } = ae(H());
    function u(h) {
      switch (h) {
        case "add":
          return v();
        case "import":
          return a();
        case "export":
          return t();
      }
    }
    const m = A(""), r = A(!1), y = G(() => r.value || s.value), { breakpoints: w } = Fe(), x = G(() => w.value.xs || w.value.sm), I = G(() => x.value ? 10 : 20), d = Ce(), p = G(() => [
      {
        label: l("inventory.ingredient.create.title"),
        value: "add",
        isPrimary: !0,
        prependIcon: "add"
      },
      { label: l("common.import"), value: "import" },
      { label: l("common.export"), value: "export" }
    ]);
    return (h, V) => {
      const D = R("FmTable");
      return F(), M(De, {
        title: i(l)("inventory.ingredientGroup.title"),
        actions: p.value,
        "onClick:action": u
      }, {
        default: T(() => [
          c("div", {
            class: _e([
              "flex flex-col gap-8 max-h-full",
              {
                "p-0": x.value,
                "px-24 ": !x.value
              }
            ])
          }, [
            b($e, {
              searchable: "",
              search: m.value,
              "onUpdate:search": V[0] || (V[0] = (E) => m.value = E)
            }, null, 8, ["search"]),
            b(D, {
              style: be(i(d).tableHeight),
              "column-defs": i(n),
              "row-data": f.value,
              "search-value": m.value,
              loading: !i(k)._currentLocation || y.value,
              "loading-text": "Loading",
              onRowClick: V[1] || (V[1] = (E) => i(e)(E.original)),
              "page-size": I.value
            }, {
              "list-row": T((E) => [
                b(Ae, {
                  row: E,
                  onRowClick: i(e)
                }, ke({
                  default: T((N) => {
                    var J, Q, W, O, X, Z, ee, te, q, ne;
                    return [
                      c("div", kt, [
                        c("div", xt, [
                          b(i(le), {
                            render: (W = (Q = (J = N.code) == null ? void 0 : J.column) == null ? void 0 : Q.columnDef) == null ? void 0 : W.cell,
                            props: (X = (O = N.code) == null ? void 0 : O.getContext) == null ? void 0 : X.call(O)
                          }, null, 8, ["render", "props"])
                        ]),
                        c("div", ht, [
                          b(i(le), {
                            render: (te = (ee = (Z = N.name) == null ? void 0 : Z.column) == null ? void 0 : ee.columnDef) == null ? void 0 : te.cell,
                            props: (ne = (q = N.name) == null ? void 0 : q.getContext) == null ? void 0 : ne.call(q)
                          }, null, 8, ["render", "props"])
                        ])
                      ])
                    ];
                  }),
                  _: 2
                }, [
                  r.value ? {
                    name: "loading-text",
                    fn: T(() => [
                      c("div", null, $(i(l)("inventory.ingredient.table.importing")), 1)
                    ]),
                    key: "0"
                  } : void 0
                ]), 1032, ["row", "onRowClick"])
              ]),
              _: 1
            }, 8, ["style", "column-defs", "row-data", "search-value", "loading", "page-size"])
          ], 2),
          (F(), M(xe, { to: "body" }, [
            b(bt, he(we(i(g))), null, 16)
          ]))
        ]),
        _: 1
      }, 8, ["title", "actions"]);
    };
  }
});
export {
  Pt as default
};
