import { defineComponent as ie, computed as b, ref as $, reactive as Ve, watch as Ce, resolveComponent as d, createElementBlock as y, openBlock as m, Fragment as V, renderSlot as Me, createVNode as s, unref as e, withCtx as k, createBlock as T, createCommentVNode as G, createElementVNode as v, renderList as j, normalizeClass as J, createTextVNode as we, toDisplayString as U, getCurrentInstance as Ee, h as te, withModifiers as oe } from "vue";
import { useI18n as Q } from "@feedmepos/mf-common";
import { useSnackbar as W, components as se, useDialog as $e, FmButtonVariant as ue, useBreakpoints as Ue } from "@feedmepos/ui-library";
import { _ as Ne } from "./ResponsiveFabButton.vue_vue_type_script_setup_true_lang-Cn-3MRBO.js";
import { Q as re, G as X, u as Z, I as Ie, D as K, J as Oe, a5 as ce, H as le, M as q, A as H } from "./index.vue_vue_type_script_setup_true_lang-BMVa5UfU.js";
import { _ as Te } from "./PageLayout.vue_vue_type_script_setup_true_lang-2f0QfweQ.js";
import { defineStore as Be } from "pinia";
import { _ as ae, g as Le } from "./InventoryBinding.vue_vue_type_script_setup_true_lang-Z6-d-lro.js";
import { u as De } from "./discardConfirm-BHni0LNu.js";
import { c as Pe } from "./check-C9mY6LiX.js";
import { u as Re } from "./unit-qhvUQfBE.js";
import { c as Ae } from "./createComponentProgrammatically-Bt2rn1IQ.js";
const Ye = { class: "fm-typo-en-title-md-600" }, ze = {
  key: 0,
  class: "pt-8 flex flex-col gap-8"
}, Ke = {
  key: 1,
  class: "pt-8 space-y-40"
}, Ge = { class: "flex flex-row gap-16" }, je = { class: "overflow-x-hidden overflow-y-auto max-h-[300px]" }, qe = { class: "flex gap-8 items-center justify-start" }, He = /* @__PURE__ */ ie({
  __name: "Form",
  props: {
    initialValue: { default: void 0 },
    usedCodes: { default: () => [] },
    invalidSkuAndRecipe: {}
  },
  setup(B, { expose: N }) {
    const { t: l } = Q(), r = B, u = re(X(W())), S = Re(), h = b(() => r.initialValue ? l("menu.sku.update") : l("menu.sku.add")), x = b(
      () => r.initialValue ? l("menu.common.actions.update") : l("menu.common.actions.add")
    ), C = $(!1), f = $(!1), M = (t) => {
      Pe.isBoolean(t) ? f.value = t : f.value = !f.value;
    }, I = Z(), a = b(() => I.units), i = b(() => a.value.map(({ name: t, _id: o, abbrev: g, measurements: O }) => ({
      label: t,
      value: o,
      options: [
        {
          label: `${t} (${g})`,
          value: null
        },
        ...O.map(({ name: A, id: Y, abbrev: z }) => ({
          label: `${A} (${z})`,
          value: Y
        }))
      ]
    }))), c = b(() => a.value.length > 0), n = Ve(
      r.initialValue ? Ie(r.initialValue) : {
        ...K.generator.initSku(),
        unit: a.value[0] || K.generator.initUnit()
      }
    ), F = $(!!n.convert), L = b(() => {
      var o;
      const t = i.value.find((g) => g.value === n.unit._id);
      return ((o = ((t == null ? void 0 : t.options) || []).find((g) => g.value === (n.trackingMeasurement || null))) == null ? void 0 : o.label) || "";
    }), D = (t) => n.unit._id === t.value && n.trackingMeasurement === (t.value || null);
    function _(t, o) {
      const g = o || void 0;
      n.unit._id === t && n.trackingMeasurement === g || (n.unit = a.value.find((O) => O._id === t), n.trackingMeasurement = g, n.convert && (n.convert.measurement = g));
    }
    const de = b(() => {
      const t = i.value.find((o) => o.value === n.unit._id);
      return ((t == null ? void 0 : t.options) || []).map((o) => ({
        ...o,
        label: `1 ${o.label}`
      }));
    });
    function me(t) {
      var o;
      F.value && (n.convert = {
        ...n.convert,
        measurement: t || void 0,
        inventoryBindings: ((o = n.convert) == null ? void 0 : o.inventoryBindings) || []
      });
    }
    function ee(t) {
      F.value && (n.convert = {
        ...n.convert,
        inventoryBindings: t
      }), R.value = !1;
    }
    const pe = b(() => r.invalidSkuAndRecipe.skus), ve = b(() => r.invalidSkuAndRecipe.recipes);
    l("menu.sku.errors.select_recipe_ingredient");
    const R = $(!1);
    function _e() {
      var t;
      return R.value = (((t = n.convert) == null ? void 0 : t.inventoryBindings) || []).length === 0, !R.value;
    }
    const fe = De(
      () => !Oe.isEqual(n, r.initialValue || K.generator.initSku()),
      () => {
        f.value = !1;
      }
    ), be = async () => {
      try {
        if (!(F.value ? _e() : !0)) return;
        const o = {
          ...n,
          convert: F.value ? n.convert : void 0
        };
        r.initialValue ? await u.updateMenu(
          {
            module: H.F_MENU_MODULE_V4_KEY.enum.sku,
            operation: q.F_OPERATION_TYPE.update,
            data: o
          },
          o.name
        ) : await u.updateMenu(
          {
            module: H.F_MENU_MODULE_V4_KEY.enum.sku,
            operation: q.F_OPERATION_TYPE.create,
            data: o
          },
          o.name
        ), M(!1);
      } finally {
        C.value = !1;
      }
    };
    return Ce(
      () => f.value,
      (t) => {
      }
    ), N({
      show: f,
      trigger: M
    }), (t, o) => {
      const g = d("FmTextField"), O = d("FmLabel"), A = d("FmField"), Y = d("FmMenuHeader"), z = d("FmMenuDivider"), ge = d("FmMenuItem"), ye = d("FmMenu"), ke = d("FmFormGroup"), he = d("FmSwitch"), xe = d("FmSelect"), Fe = d("FmCard"), ne = d("fm-button"), Se = d("fm-side-sheet");
      return m(), y(V, null, [
        Me(t.$slots, "default", { trigger: M }),
        s(Se, {
          id: "unit-form",
          modelValue: f.value,
          "onUpdate:modelValue": o[4] || (o[4] = (p) => f.value = p),
          "is-container": e(se).FmForm,
          "is-container-props": {
            onValidationSuccess: be,
            blameFormChildOnValidationFailed: !0
          },
          "max-width": 560,
          "onOn:clickedAway": e(fe)
        }, {
          "side-sheet-header": k(() => [
            v("p", Ye, U(h.value), 1)
          ]),
          "side-sheet-footer": k(() => [
            v("div", qe, [
              s(ne, {
                label: x.value,
                loading: C.value,
                size: "lg",
                type: "submit",
                variant: "primary"
              }, null, 8, ["label", "loading"]),
              s(ne, {
                label: e(l)("menu.common.actions.cancel"),
                size: "lg",
                variant: "tertiary",
                onClick: o[3] || (o[3] = () => f.value = !1)
              }, null, 8, ["label"])
            ])
          ]),
          default: k(() => [
            c.value ? (m(), y("div", Ke, [
              v("div", Ge, [
                s(g, {
                  class: "flex-2",
                  label: e(l)("menu.sku.columns.code"),
                  modelValue: n.code,
                  "onUpdate:modelValue": o[0] || (o[0] = (p) => n.code = p),
                  rules: [
                    (p) => !!p || e(l)("menu.common.validation.required", {
                      field: e(l)("menu.sku.columns.code").toLowerCase()
                    }),
                    (p) => !t.usedCodes.includes(p.trim()) || e(l)("menu.sku.validation.code_used")
                  ]
                }, null, 8, ["label", "modelValue", "rules"]),
                s(g, {
                  class: "flex-1",
                  label: e(l)("menu.sku.columns.name"),
                  modelValue: n.name,
                  "onUpdate:modelValue": o[1] || (o[1] = (p) => n.name = p),
                  rules: [
                    (p) => p ? !0 : e(l)("menu.common.validation.required", {
                      field: e(l)("menu.sku.columns.name").toLowerCase()
                    })
                  ]
                }, null, 8, ["label", "modelValue", "rules"])
              ]),
              s(ke, {
                class: "col-span-2",
                "label-mark": "required",
                "model-value": L.value
              }, {
                label: k(() => [
                  s(O, {
                    label: e(l)("menu.sku.columns.unit")
                  }, null, 8, ["label"])
                ]),
                default: k(({ invalid: p }) => [
                  s(ye, { "z-index": 101 }, {
                    "menu-button": k(() => [
                      s(A, {
                        class: J([
                          "fm-typo-en-body-lg-400",
                          {
                            "text-fm-color-typo-primary": !0
                          }
                        ]),
                        invalid: p,
                        "append-icon": "expand_more"
                      }, {
                        default: k(() => [
                          we(U(L.value), 1)
                        ]),
                        _: 2
                      }, 1032, ["invalid"])
                    ]),
                    default: k(() => [
                      v("div", je, [
                        (m(!0), y(V, null, j(i.value, (w, P) => (m(), y(V, { key: P }, [
                          s(Y, {
                            label: w.label
                          }, null, 8, ["label"]),
                          s(z),
                          (m(!0), y(V, null, j(w.options, (E, dn) => (m(), T(ge, {
                            label: E.label,
                            "model-value": D(E),
                            onClick: (mn) => _(w.value, E.value),
                            "x-should-scroll-into": `${D(E)}`
                          }, null, 8, ["label", "model-value", "onClick", "x-should-scroll-into"]))), 256))
                        ], 64))), 128))
                      ])
                    ]),
                    _: 2
                  }, 1024)
                ]),
                _: 1
              }, 8, ["model-value"]),
              s(Fe, {
                variant: "outlined",
                class: "p-16 flex flex-col gap-16"
              }, {
                default: k(() => {
                  var p, w, P;
                  return [
                    s(he, {
                      value: "",
                      "model-value": F.value,
                      "onUpdate:modelValue": o[2] || (o[2] = (E) => F.value = E),
                      label: e(l)("menu.sku.convertible.label"),
                      sublabel: e(l)("menu.sku.convertible.sublabel"),
                      labelPlacement: "right"
                    }, null, 8, ["model-value", "label", "sublabel"]),
                    F.value ? (m(), y(V, { key: 0 }, [
                      v("div", null, [
                        s(xe, {
                          label: e(l)("menu.sku.convertible.convert_to"),
                          modelValue: ((p = n.convert) == null ? void 0 : p.measurement) || null,
                          "onUpdate:modelValue": me,
                          items: de.value
                        }, null, 8, ["label", "modelValue", "items"])
                      ]),
                      s(ae, {
                        "model-value": ((w = n.convert) == null ? void 0 : w.inventoryBindings) || [],
                        type: e(le.F_INVENTORY_BINDING_TYPE).enum.RECIPE,
                        "filter-option-ids": ve.value,
                        "onUpdate:modelValue": ee
                      }, null, 8, ["model-value", "type", "filter-option-ids"]),
                      s(ae, {
                        "model-value": ((P = n.convert) == null ? void 0 : P.inventoryBindings) || [],
                        type: e(le.F_INVENTORY_BINDING_TYPE).enum.SKU,
                        "filter-option-ids": pe.value,
                        "onUpdate:modelValue": ee
                      }, null, 8, ["model-value", "type", "filter-option-ids"])
                    ], 64)) : G("", !0)
                  ];
                }),
                _: 1
              })
            ])) : (m(), y("div", ze, [
              a.value.length === 0 ? (m(), T(e(ce), {
                key: 0,
                action: {
                  text: e(l)("menu.unit.add"),
                  callback() {
                    e(S).createUnit();
                  }
                },
                subtitle: e(l)("menu.sku.empty.subtitle"),
                title: e(l)("menu.sku.empty.no_unit")
              }, null, 8, ["action", "subtitle", "title"])) : G("", !0)
            ]))
          ]),
          _: 1
        }, 8, ["modelValue", "is-container", "is-container-props", "onOn:clickedAway"])
      ], 64);
    };
  }
}), Je = He, Qe = Be("sku-manager", () => {
  const B = $e(), N = W(), l = X(N), r = re(l), u = Z(), S = Ee(), { t: h } = Q(), x = (a) => {
    var c, n;
    const { vNode: i } = Ae(
      Je,
      S,
      a
    );
    (n = (c = i.component) == null ? void 0 : c.exposed) == null || n.trigger();
  };
  async function C(a) {
    x({
      initialValue: a,
      usedCodes: u.skus.filter(({ _id: i }) => i !== (a == null ? void 0 : a._id)).map((i) => i.code),
      invalidSkuAndRecipe: a ? Le({
        id: a._id,
        skus: u.skus,
        recipes: u.state.menu.modules.recipe
      }) : { skus: [], recipes: [] }
    });
  }
  async function f() {
    C();
  }
  async function M(a) {
    C(a);
  }
  async function I(a) {
    B.open({
      title: h("menu.common.dialog.remove.ingredient.title"),
      message: h("menu.common.dialog.remove.ingredient.message", { name: a.name }),
      primaryActions: {
        text: h("menu.common.actions.remove"),
        close: !0,
        variant: ue.Destructive
      },
      secondaryActions: {
        text: h("menu.common.actions.cancel"),
        close: !0
      }
    }).onPrimary(async () => {
      await r.updateMenu(
        {
          module: H.F_MENU_MODULE_V4_KEY.enum.sku,
          operation: q.F_OPERATION_TYPE.delete,
          data: a._id
        },
        a.name,
        !0
      );
    });
  }
  return {
    createSku: f,
    updateSku: M,
    deleteSku: I
  };
}), We = {
  key: 0,
  class: "h-[600px]"
}, Xe = {
  class: "flex justify-end items-center"
}, Ze = {
  class: "flex items-center my-8 px-16"
}, en = {
  class: /* @__PURE__ */ J(["flex-1", "overflow-scroll", "divide-y divide-fm-color-neutral-gray-100", "pb-64"])
}, nn = ["onClick"], tn = {
  class: "flex-1"
}, on = {
  class: "fm-typo-en-body-lg-600 mb-4"
}, ln = {
  class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary"
}, an = {
  class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary"
}, sn = {
  class: "flex-1 flex justify-between gap-8 pl-8"
}, un = {
  class: "flex items-center"
}, rn = {
  class: "bg-fm-color-neutral-gray-100 rounded-md px-8 py-4"
}, cn = {
  class: "fm-typo-en-body-md-600 font-semibold"
}, Vn = /* @__PURE__ */ ie({
  __name: "Ingredient",
  setup(B) {
    const N = W();
    X(N);
    const l = Z(), r = Qe(), {
      t: u
    } = Q(), S = b(() => l.skus), h = b(() => S.value.filter((i) => `${i.name} ${i.code} ${i._unit} (${i._abbrev})`.toLowerCase().includes(x.value.toLowerCase()))), x = $(""), C = $([{
      accessorKey: "code",
      header: () => u("menu.ingredient.table.columns.code"),
      enableSorting: !1
    }, {
      accessorKey: "name",
      header: () => u("menu.ingredient.table.columns.name"),
      enableSorting: !1
    }, {
      accessorKey: "unit",
      header: () => u("menu.ingredient.table.columns.unit"),
      enableSorting: !1,
      cell: (i) => {
        const c = i.row.original;
        return `${c._unit} (${c._abbrev})`;
      }
    }, {
      id: "actions",
      size: 52,
      meta: {
        cellClass: "pl-16",
        headerContentClass: "-mx-16"
      },
      header: "",
      cell: (i) => {
        const c = i.row.original;
        return te("div", {
          class: "flex justify-end"
        }, [te(se.FmButton, {
          icon: "delete",
          textColor: "neutral-gray-400",
          variant: "tertiary",
          onClick: oe(async () => {
            r.deleteSku(c);
          }, ["stop", "prevent"])
        })]);
      }
    }]);
    function f(i) {
      r.updateSku(i);
    }
    const M = b(() => S.value.length), I = Ue(), a = b(() => I.breakpoints.value.xs);
    return (i, c) => {
      const n = d("FmSearch"), F = d("FmTable"), L = d("fm-button"), D = d("FmSpacer");
      return m(), T(Te, {
        heading: e(u)("menu.ingredient.title")
      }, {
        default: k(() => [S.value.length === 0 ? (m(), T(e(ce), {
          key: 0,
          action: {
            text: e(u)("menu.ingredient.empty.action"),
            callback() {
              e(r).createSku();
            }
          },
          subtitle: e(u)("menu.ingredient.empty.subtitle"),
          title: e(u)("menu.ingredient.empty.title")
        }, null, 8, ["action", "subtitle", "title"])) : (m(), y(V, {
          key: 1
        }, [a.value ? (m(), y(V, {
          key: 1
        }, [v("div", Ze, [s(n, {
          autofocus: "",
          modelValue: x.value,
          "onUpdate:modelValue": c[2] || (c[2] = (_) => x.value = _),
          placeholder: e(u)("menu.ingredient.table.search.placeholder"),
          class: "w-full"
        }, null, 8, ["modelValue", "placeholder"])]), v("div", en, [(m(!0), y(V, null, j(h.value, (_) => (m(), y("div", {
          key: _._id,
          class: J(["py-12 px-16", "flex  space-x-8", "items-center"]),
          onClick: () => e(r).updateSku(_)
        }, [v("div", tn, [v("p", on, U(_.name), 1), v("p", ln, U(e(u)("menu.ingredient.table.mobile.code", {
          code: _.code
        })), 1), v("p", an, U(e(u)("menu.ingredient.table.mobile.unit", {
          unit: `${_._unit} (${_._abbrev})`
        })), 1)]), s(L, {
          variant: e(ue).Tertiary,
          "prepend-icon": "delete",
          "text-color": "neutral-gray-400",
          onClick: oe(() => e(r).deleteSku(_), ["stop"])
        }, null, 8, ["variant", "onClick"])], 8, nn))), 128))])], 64)) : (m(), y("div", We, [v("div", Xe, [s(n, {
          autofocus: "",
          modelValue: x.value,
          "onUpdate:modelValue": c[0] || (c[0] = (_) => x.value = _),
          class: "mb-8 w-[320px]",
          placeholder: e(u)("menu.ingredient.table.search.placeholder")
        }, null, 8, ["modelValue", "placeholder"])]), s(F, {
          "column-defs": C.value,
          "row-data": h.value,
          "page-size": h.value.length,
          "shrink-at": !1,
          "hide-footer": "",
          "pin-header-row": "",
          onRowClick: c[1] || (c[1] = (_) => f(_.original))
        }, null, 8, ["column-defs", "row-data", "page-size"])]))], 64))]),
        "append-heading": k(() => [v("div", sn, [v("div", un, [v("div", rn, [v("p", cn, U(M.value), 1)])]), s(D), S.value.length > 0 ? (m(), T(Ne, {
          key: 0,
          label: e(u)("menu.ingredient.actions.add"),
          "prepend-icon": "add",
          onClick: e(r).createSku
        }, null, 8, ["label", "onClick"])) : G("", !0)])]),
        _: 1
      }, 8, ["heading"]);
    };
  }
});
export {
  Vn as default
};
