import { defineComponent as O, computed as b, openBlock as v, createElementBlock as w, createElementVNode as s, Fragment as K, renderList as G, toDisplayString as h, createCommentVNode as Q, ref as I, watch as oe, resolveComponent as $, createBlock as T, withCtx as A, createVNode as f, unref as i, isRef as le, normalizeClass as me, normalizeStyle as ce, Teleport as pe, normalizeProps as ve, guardReactiveProps as fe } from "vue";
import { a as Y, S as ye, c as ie, w as be, i as se, u as ge } from "./app-Bpb4394e.js";
import { useDialog as ue, useSnackbar as Z, useProxiedModel as ae, useBreakpoints as xe } from "@feedmepos/ui-library";
import { i as _e, _ as he } from "./is-linked-ingredient-error-fJ2TJb3z.js";
import { F as U } from "./form-mode.enum-BKiNVH6A.js";
import { defineStore as Ve, storeToRefs as Ue } from "pinia";
import { D as re, R as q } from "./row-action.enum-DQ9bJ_uv.js";
import { c as we } from "./component-kqxARxvM.js";
import { useI18n as J } from "@feedmepos/mf-common";
import { u as Ce, _ as Se } from "./SingleColumnLayout.vue_vue_type_script_setup_true_lang-sUxHOj47.js";
import { R as H, A as Fe, c as ke } from "./rules-CoimOM7X.js";
import { a as W, c as Ee } from "./number-BVg7EKPV.js";
import { F as $e } from "./decimal-C219qGO5.js";
import { _ as Ie } from "./NumberPrecisionInput.vue_vue_type_script_setup_true_lang-C50b1vbd.js";
import { _ as Ae, F as De } from "./TableActionableRow.vue_vue_type_script_setup_true_lang-Ca_eYa8-.js";
import { _ as Re } from "./FmInventoryTableToolbar.vue_vue_type_script_setup_true_lang-j3aDZ2cT.js";
import { u as Me } from "./netsuite-BGUUAOqe.js";
const Pe = { class: "flex flex-col gap-8" }, Te = {
  key: 0,
  class: "flex flex-col"
}, Be = { class: "flex-1 py-8 px-16" }, Le = {
  class: "flex-0 py-8 px-16",
  style: { "flex-basis": "240px" }
}, Ne = {
  key: 1,
  class: "flex flex-col"
}, ze = { class: "flex-1 py-8 px-16" }, je = {
  class: "flex-0 py-8 px-16",
  style: { "flex-basis": "240px" }
}, qe = {
  key: 2,
  class: "flex flex-col"
}, He = { class: "flex-1 py-8 px-16" }, Ke = {
  class: "flex-0 py-8 px-16",
  style: { "flex-basis": "240px" }
}, Ge = /* @__PURE__ */ O({
  __name: "UnitUsedBy",
  props: {
    unit: {}
  },
  setup(S) {
    const c = S, g = Y(), m = b(() => g.validateUnitUsage(c.unit)), l = b(() => m.value.filter((n) => n.from === "INGREDIENT")), a = b(() => m.value.filter((n) => n.from === "RECIPE")), d = b(() => m.value.filter((n) => n.from === "MENU"));
    return (n, p) => (v(), w("div", Pe, [
      p[3] || (p[3] = s("div", { class: "fm-typo-en-body-md-400" }, "Sorry, this unit is used in the following modules:", -1)),
      l.value.length ? (v(), w("div", Te, [
        p[0] || (p[0] = s("div", { class: "flex flex-row fm-typo-en-body-md-600 bg-fm-color-neutral-gray-100 text-fm-color-typo-secondary h-48 items-center" }, [
          s("div", { class: "flex-1 py-8 px-16" }, "Ingredient"),
          s("div", {
            class: "flex-0 py-8 px-16",
            style: { "flex-basis": "240px" }
          }, "Used in")
        ], -1)),
        (v(!0), w(K, null, G(l.value, (r) => {
          var t;
          return v(), w("div", {
            key: r.code,
            class: "flex flex-row fm-typo-en-body-md-400 h-48 items-center border-b border-b-fm-color-neutral-gray-100"
          }, [
            s("div", Be, h(r.code) + " " + h(r.name), 1),
            s("div", Le, h((t = r.bindedIngredient) != null && t.length ? "Convert binding" : "Item unit"), 1)
          ]);
        }), 128))
      ])) : Q("", !0),
      a.value.length ? (v(), w("div", Ne, [
        p[1] || (p[1] = s("div", { class: "flex flex-row fm-typo-en-body-md-600 bg-fm-color-neutral-gray-100 text-fm-color-typo-secondary h-48 items-center" }, [
          s("div", { class: "flex-1 py-8 px-16" }, "Recipe"),
          s("div", {
            class: "flex-0 py-8 px-16",
            style: { "flex-basis": "240px" }
          }, "Used in")
        ], -1)),
        (v(!0), w(K, null, G(a.value, (r) => {
          var t, u, y;
          return v(), w("div", {
            key: r.code,
            class: "flex flex-row fm-typo-en-body-md-400 h-48 items-center border-b border-b-fm-color-neutral-gray-100"
          }, [
            s("div", ze, h(r.code) + " " + h(r.name), 1),
            s("div", je, h((t = r.bindedIngredient) == null ? void 0 : t.slice(0, 3).map((F) => F.code).join(", ")) + " " + h(r.bindedIngredient && ((u = r.bindedIngredient) == null ? void 0 : u.length) > 3 ? `and ${((y = r.bindedIngredient) == null ? void 0 : y.length) - 3} more` : ""), 1)
          ]);
        }), 128))
      ])) : Q("", !0),
      d.value.length ? (v(), w("div", qe, [
        p[2] || (p[2] = s("div", { class: "flex flex-row fm-typo-en-body-md-600 bg-fm-color-neutral-gray-100 text-fm-color-typo-secondary h-48 items-center" }, [
          s("div", { class: "flex-1 py-8 px-16" }, "Menu"),
          s("div", {
            class: "flex-0 py-8 px-16",
            style: { "flex-basis": "240px" }
          }, "Used in")
        ], -1)),
        (v(!0), w(K, null, G(d.value, (r) => {
          var t, u, y;
          return v(), w("div", {
            key: r.code,
            class: "flex flex-row fm-typo-en-body-md-400 h-48 items-center border-b border-b-fm-color-neutral-gray-100"
          }, [
            s("div", He, h(r.code) + " " + h(r.name), 1),
            s("div", Ke, h((t = r.bindedIngredient) == null ? void 0 : t.slice(0, 3).map((F) => F.code).join(", ")) + " " + h(r.bindedIngredient && ((u = r.bindedIngredient) == null ? void 0 : u.length) > 3 ? `and ${((y = r.bindedIngredient) == null ? void 0 : y.length) - 3} more` : ""), 1)
          ]);
        }), 128))
      ])) : Q("", !0)
    ]));
  }
}), X = Ve("unitForm", function() {
  const c = ue(), g = Z(), m = Y(), l = I(!1), a = I();
  function d() {
    const t = {
      unit: {},
      mode: U.CREATE,
      show: !0,
      "onUpdate:show"(u) {
        a.value.show = u;
      }
    };
    a.value = t;
  }
  async function n(t) {
    const u = {
      unit: t,
      mode: U.UPDATE,
      show: !0,
      "onUpdate:show"(y) {
        a.value.show = y;
      }
    };
    a.value = u;
  }
  async function p(t) {
    l.value = !0;
    try {
      await m.deleteUnit(t), g.open({
        title: "Success",
        message: `Deleted ${t.name}`,
        type: "success"
      });
    } catch (u) {
      u instanceof ye && _e(u) ? c.open({
        title: "Cannot delete unit",
        contentComponent: he,
        contentComponentProps: {
          subject: (t == null ? void 0 : t.name) ?? "",
          items: u.errorResponse.message
        },
        secondaryActions: {
          text: "Close",
          close: !0
        }
      }) : console.log("unable to delete unit", u), g.open({
        title: `Cannot delete ${t.name}`,
        message: "Please try again.",
        type: "error"
      }), console.error("failed to delete unit", u);
    } finally {
      l.value = !1;
    }
  }
  function r(t) {
    if (m.validateUnitUsage(t).length) {
      c.open({
        title: `Cannot delete ${(t == null ? void 0 : t.name) ?? "unit"}`,
        overlay: !0,
        dismissAway: !0,
        closeButton: !0,
        contentComponent: Ge,
        contentComponentProps: {
          unit: t
        },
        primaryActions: {
          text: "Confirm",
          close: !0
        }
      });
      return;
    }
    c.open({
      title: `Delete ${(t == null ? void 0 : t.name) ?? "unit"}?`,
      closeButton: !1,
      message: "You may not be able to delete this unit if it is linked in any of the inventory modules.",
      primaryActions: {
        text: "Delete",
        close: !0,
        variant: "destructive"
      },
      secondaryActions: {
        text: "Cancel",
        close: !0
      }
    }).onPrimary(() => p(t));
  }
  return {
    createUnit: d,
    updateUnit: n,
    deleteUnit: r,
    unitDialogProps: a,
    unitViewLoading: l
  };
});
function Oe() {
  const { updateUnit: S, deleteUnit: c } = X(), { t: g } = J();
  async function m(a, d) {
    const n = ie(d);
    if (a === q.Edit) {
      await S(n);
      return;
    }
    if (a === q.Delete) {
      await c(n);
      return;
    }
  }
  return { columnDefs: [
    {
      accessorKey: "name",
      header: g("inventory.unit.table.name"),
      enableSorting: !0,
      size: 300
    },
    {
      accessorKey: "abbrev",
      header: g("inventory.unit.table.symbol"),
      enableSorting: !1,
      size: "auto"
    },
    {
      id: "action",
      header: "",
      cell(a) {
        return we(
          [re[q.Edit], re[q.Delete]],
          (d) => {
            m(d, a.row.original);
          }
        );
      },
      enableSorting: !1,
      size: 40,
      meta: {
        cellClass: "",
        headerClass: ""
      }
    }
  ] };
}
const Ye = { class: "flex flex-col gap-24" }, Je = { class: "flex gap-24" }, Qe = { class: "flex-1" }, We = { class: "flex-1" }, Xe = { class: "flex" }, Ze = { class: "flex items-center" }, et = { class: "fm-typo-en-body-lg-600 flex-grow" }, tt = { class: "flex flex-col gap-24" }, nt = { class: "flex gap-24" }, ot = { class: "flex-1" }, lt = { class: "flex-1" }, st = /* @__PURE__ */ O({
  __name: "UnitForm",
  props: {
    mode: {},
    modelValue: {},
    disabled: { type: Boolean }
  },
  emits: ["update:modelValue", "click:submit"],
  setup(S, { expose: c, emit: g }) {
    const m = S, l = g, { t: a } = J();
    function d() {
      l("click:submit");
    }
    const n = I(m.modelValue);
    oe(
      () => m.modelValue,
      (e) => {
        n.value = e;
      }
    );
    const p = b({
      get() {
        var e;
        return ((e = n.value) == null ? void 0 : e.name) ?? "";
      },
      set(e) {
        n.value.name = e, l("update:modelValue", n.value);
      }
    }), r = b({
      get() {
        var e;
        return ((e = n.value) == null ? void 0 : e.abbrev) ?? "";
      },
      set(e) {
        n.value.abbrev = e, l("update:modelValue", n.value);
      }
    }), t = b({
      get() {
        var e;
        return ((e = n.value) == null ? void 0 : e.precision) ?? 0;
      },
      set(e) {
        n.value.precision = e, l("update:modelValue", n.value);
      }
    }), u = b({
      get() {
        var e;
        return ((e = n.value) == null ? void 0 : e.measurements) ?? [];
      },
      set(e) {
        n.value.measurements = e, l("update:modelValue", n.value);
      }
    });
    oe(
      () => t.value,
      (e) => {
        if (typeof e == "number" && !isNaN(e)) {
          const o = u.value.map((V) => ({
            ...V,
            conversion: be.convertPrecision({
              value: V.conversion,
              precision: e
            })
          }));
          n.value.measurements = o, l("update:modelValue", n.value);
        }
      },
      { immediate: !0 }
    );
    function y() {
      const e = n.value.measurements ?? [];
      n.value.measurements = [
        ...e,
        {
          id: `measurement_${(/* @__PURE__ */ new Date()).toISOString()}_${Math.random().toString(16).slice(2, 8)}`,
          name: "",
          abbrev: "",
          conversion: {
            amount: 1,
            precision: 0
          }
        }
      ], l("update:modelValue", n.value);
    }
    function F(e) {
      const o = n.value.measurements ?? [];
      o.splice(e, 1), n.value.measurements = o, l("update:modelValue", n.value);
    }
    const E = I();
    return c({
      validateInputs: () => {
        var e, o;
        (o = (e = E.value) == null ? void 0 : e.validateInputs) == null || o.call(e);
      },
      resetInputsValidation: () => {
        var e, o;
        (o = (e = E.value) == null ? void 0 : e.resetInputsValidation) == null || o.call(e);
      },
      resetInputs: () => {
        var e, o;
        (o = (e = E.value) == null ? void 0 : e.resetInputs) == null || o.call(e);
      }
    }), (e, o) => {
      const V = $("FmTextField"), R = $("FmStepperField"), C = $("FmButton"), M = $("FmCard"), D = $("FmForm");
      return v(), T(D, {
        ref_key: "formRef",
        ref: E,
        class: "flex flex-col gap-40",
        onValidationSuccess: d
      }, {
        default: A(() => {
          var B;
          return [
            s("div", Ye, [
              s("div", Je, [
                s("div", Qe, [
                  f(V, {
                    disabled: e.disabled,
                    label: i(a)("inventory.unit.name"),
                    modelValue: p.value,
                    "onUpdate:modelValue": o[0] || (o[0] = (x) => p.value = x),
                    rules: [i(H)()],
                    "label-mark": "required"
                  }, null, 8, ["disabled", "label", "modelValue", "rules"])
                ]),
                s("div", We, [
                  f(V, {
                    disabled: e.disabled,
                    label: i(a)("inventory.unit.symbol"),
                    modelValue: r.value,
                    "onUpdate:modelValue": o[1] || (o[1] = (x) => r.value = x),
                    rules: [i(H)()],
                    "label-mark": "required"
                  }, null, 8, ["disabled", "label", "modelValue", "rules"])
                ])
              ]),
              s("div", null, [
                f(R, {
                  disabled: e.disabled,
                  class: "col-span-3",
                  label: i(a)("inventory.unit.precision"),
                  modelValue: t.value,
                  "onUpdate:modelValue": o[2] || (o[2] = (x) => t.value = x),
                  rules: [i(Fe)(0)]
                }, null, 8, ["disabled", "label", "modelValue", "rules"])
              ])
            ]),
            s("div", Xe, [
              f(C, {
                disabled: e.disabled,
                type: "button",
                "prepend-icon": "add",
                label: i(a)("inventory.unit.measurement.addMeasurement"),
                variant: "plain",
                onClick: y
              }, null, 8, ["disabled", "label"])
            ]),
            (v(!0), w(K, null, G((B = e.modelValue) == null ? void 0 : B.measurements, (x, _) => (v(), T(M, {
              class: "flex flex-col gap-16 p-16",
              variant: "outlined",
              key: x.id
            }, {
              default: A(() => [
                s("div", Ze, [
                  s("div", et, h(i(a)("inventory.unit.measurement.measurementDefault", [_ + 1])), 1),
                  f(C, {
                    disabled: e.disabled,
                    variant: "tertiary",
                    "prepend-icon": "delete",
                    onClick: (k) => F(_)
                  }, null, 8, ["disabled", "onClick"])
                ]),
                s("div", tt, [
                  s("div", nt, [
                    s("div", ot, [
                      f(V, {
                        disabled: e.disabled,
                        class: "col-span-2",
                        label: i(a)("inventory.unit.measurement.name"),
                        modelValue: e.modelValue.measurements[_].name,
                        "onUpdate:modelValue": (k) => e.modelValue.measurements[_].name = k,
                        rules: [i(H)()],
                        "label-mark": "required"
                      }, null, 8, ["disabled", "label", "modelValue", "onUpdate:modelValue", "rules"])
                    ]),
                    s("div", lt, [
                      f(V, {
                        disabled: e.disabled,
                        label: i(a)("inventory.unit.measurement.symbol"),
                        modelValue: e.modelValue.measurements[_].abbrev,
                        "onUpdate:modelValue": (k) => e.modelValue.measurements[_].abbrev = k,
                        rules: [i(H)()],
                        "label-mark": "required"
                      }, null, 8, ["disabled", "label", "modelValue", "onUpdate:modelValue", "rules"])
                    ])
                  ]),
                  f(Ie, {
                    disabled: e.disabled,
                    class: "col-span-3",
                    label: i(a)("inventory.unit.measurement.conversion"),
                    "model-value": +i(W)(e.modelValue.measurements[_].conversion),
                    "onUpdate:modelValue": (k) => u.value = u.value.map(
                      (P, L) => L === _ ? {
                        ...P,
                        conversion: i($e).toPrecision(
                          i(Ee)(k),
                          t.value
                        )
                      } : P
                    ),
                    rules: [i(ke)(0)],
                    step: +i(W)({ amount: 1, precision: t.value }),
                    "helper-text": i(a)("inventory.unit.measurement.conversionHelper", {
                      measurementSymbol: e.modelValue.measurements[_].name || " measurement unit",
                      conversion: +i(W)(e.modelValue.measurements[_].conversion),
                      unitSymbol: r.value || "base unit"
                    })
                  }, null, 8, ["disabled", "label", "model-value", "onUpdate:modelValue", "rules", "step", "helper-text"])
                ])
              ]),
              _: 2
            }, 1024))), 128))
          ];
        }),
        _: 1
      }, 512);
    };
  }
}), at = { class: "flex gap-4" }, rt = /* @__PURE__ */ O({
  __name: "UnitDialog",
  props: {
    show: { type: Boolean },
    unit: {},
    mode: { default: U.READ }
  },
  emits: ["update:show"],
  setup(S) {
    const c = S, g = Y(), m = Z(), { t: l } = J(), a = ae(c, "show"), d = ae(c, "unit"), n = b(() => {
      switch (c.mode) {
        case U.READ:
          return "";
        case U.UPDATE:
          return l("inventory.unit.update.title");
        case U.CREATE:
          return l("inventory.unit.create.title");
      }
      return "";
    }), p = b(() => {
      switch (c.mode) {
        case U.READ:
          return "";
        case U.UPDATE:
          return l("common.save");
        case U.CREATE:
          return l("common.add");
      }
      return "";
    }), r = I(), t = I(!1);
    async function u() {
      t.value = !0;
      try {
        const e = ie(d.value);
        e.precision ?? (e.precision = 0), e.measurements ?? (e.measurements = []), await g.createUnit(e), a.value = !1, m.open({
          title: l("inventory.common.success"),
          message: l("inventory.unit.create.success", { name: d.value.name }),
          type: "success"
        });
      } catch (e) {
        e instanceof se || m.open({
          title: l("inventory.unit.create.error.title"),
          message: l("inventory.unit.create.error.message"),
          type: "error"
        });
      } finally {
        t.value = !1;
      }
    }
    async function y() {
      t.value = !0;
      try {
        await g.updateUnit(d.value), a.value = !1, m.open({
          title: l("inventory.common.success"),
          message: l("inventory.unit.update.success", { name: d.value.name }),
          type: "success"
        });
      } catch (e) {
        e instanceof se || m.open({
          title: l("inventory.unit.update.error.title"),
          message: l("inventory.unit.update.error.message"),
          type: "error"
        });
      } finally {
        t.value = !1;
      }
    }
    function F() {
      var e, o;
      (o = (e = r.value) == null ? void 0 : e.validateInputs) == null || o.call(e);
    }
    function E() {
      switch (c.mode) {
        case U.READ:
          return;
        case U.UPDATE:
          return y();
        case U.CREATE:
          return u();
      }
    }
    return (e, o) => {
      const V = $("FmButton"), R = $("FmSideSheet");
      return v(), T(R, {
        "model-value": i(a),
        "onUpdate:modelValue": o[3] || (o[3] = (C) => le(a) ? a.value = C : null),
        header: n.value,
        "close-button": "",
        "dismiss-away": "",
        "max-width": 500
      }, {
        "side-sheet-footer": A(() => [
          s("div", at, [
            f(V, {
              loading: t.value,
              label: p.value,
              onClick: F
            }, null, 8, ["loading", "label"]),
            f(V, {
              disabled: t.value,
              label: i(l)("common.close"),
              variant: "tertiary",
              onClick: o[2] || (o[2] = (C) => a.value = !1)
            }, null, 8, ["disabled", "label"])
          ])
        ]),
        default: A(() => [
          f(st, {
            class: "w-full",
            ref_key: "hasValidationExpose",
            ref: r,
            modelValue: i(d),
            "onUpdate:modelValue": o[0] || (o[0] = (C) => le(d) ? d.value = C : null),
            mode: e.mode,
            disabled: t.value,
            "onClick:submit": o[1] || (o[1] = (C) => E())
          }, null, 8, ["modelValue", "mode", "disabled"])
        ]),
        _: 1
      }, 8, ["model-value", "header"]);
    };
  }
}), it = { class: "flex flex-col py-8" }, ut = { class: "fm-typo-en-body-lg-600 text-fm-color-typo-primary" }, dt = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, kt = /* @__PURE__ */ O({
  __name: "UnitView",
  setup(S) {
    const c = Y(), g = ge(), m = Me();
    ue(), Z();
    const { t: l } = J(), a = b(() => c.units), { createUnit: d, updateUnit: n } = X(), { unitDialogProps: p, unitViewLoading: r } = Ue(X()), { columnDefs: t } = Oe();
    function u(M) {
      switch (M) {
        case "add":
          return m.isEnabled ? void 0 : d();
      }
    }
    const y = I(""), F = I(!1), E = b(() => F.value || r.value), { breakpoints: e } = xe(), o = b(() => e.value.xs || e.value.sm), V = b(() => o.value ? 10 : 20), R = Ce(), C = b(() => [
      ...m.isEnabled ? [] : [
        {
          label: l("inventory.unit.create.title"),
          value: "add",
          isPrimary: !0,
          prependIcon: "add"
        }
      ]
    ]);
    return (M, D) => {
      const B = $("FmTable");
      return v(), T(Se, {
        title: i(l)("inventory.unit.title"),
        actions: C.value,
        "onClick:action": u
      }, {
        default: A(() => [
          s("div", {
            class: me([
              "flex flex-col gap-8 max-h-full",
              {
                "p-0": o.value,
                "px-24 ": !o.value
              }
            ])
          }, [
            f(Re, {
              searchable: "",
              search: y.value,
              "onUpdate:search": D[0] || (D[0] = (x) => y.value = x)
            }, null, 8, ["search"]),
            f(B, {
              style: ce(i(R).tableHeight),
              "column-defs": i(t),
              "row-data": a.value,
              "search-value": y.value,
              loading: !i(g)._currentLocation || E.value,
              onRowClick: D[1] || (D[1] = (x) => i(n)(x.original)),
              "page-size": V.value
            }, {
              "list-row": A((x) => [
                f(Ae, {
                  row: x,
                  onRowClick: i(n)
                }, {
                  default: A((_) => {
                    var k, P, L, N, ee, z, te, j, ne;
                    return [
                      s("div", it, [
                        s("div", ut, [
                          f(i(De), {
                            render: (L = (P = (k = _.name) == null ? void 0 : k.column) == null ? void 0 : P.columnDef) == null ? void 0 : L.cell,
                            props: (ee = (N = _.name) == null ? void 0 : N.getContext) == null ? void 0 : ee.call(N)
                          }, null, 8, ["render", "props"])
                        ]),
                        s("div", dt, h((ne = (j = (te = (z = x.original.measurements) == null ? void 0 : z.map) == null ? void 0 : te.call(z, (de) => de.name)) == null ? void 0 : j.join) == null ? void 0 : ne.call(j, ", ")), 1)
                      ])
                    ];
                  }),
                  _: 2
                }, 1032, ["row", "onRowClick"])
              ]),
              _: 1
            }, 8, ["style", "column-defs", "row-data", "search-value", "loading", "page-size"])
          ], 2),
          (v(), T(pe, { to: "body" }, [
            f(rt, ve(fe(i(p))), null, 16)
          ]))
        ]),
        _: 1
      }, 8, ["title", "actions"]);
    };
  }
});
export {
  kt as default
};
