import { defineComponent as H, ref as I, computed as L, resolveComponent as h, createElementBlock as g, openBlock as d, Fragment as x, renderSlot as ae, createVNode as l, unref as t, withCtx as m, createElementVNode as y, toDisplayString as z, onBeforeMount as oe, watch as F, watchEffect as se, h as $, getCurrentInstance as le, onMounted as re, createBlock as j, createCommentVNode as G, isRef as ie, normalizeClass as J, renderList as ue } from "vue";
import { useRouter as ce } from "vue-router";
import { I as Q, u as W, G as X, Q as Z, M as O, A as S, a5 as de } from "./index.vue_vue_type_script_setup_true_lang-BMVa5UfU.js";
import { useI18n as ee, ItemSelector as me, useCoreStore as pe } from "@feedmepos/mf-common";
import { useSnackbar as ne, components as Y, useDialog as _e, FmButtonVariant as A, useBreakpoints as fe } from "@feedmepos/ui-library";
import { _ as ge } from "./ResponsiveFabButton.vue_vue_type_script_setup_true_lang-Cn-3MRBO.js";
import { _ as ve, R as he } from "./app-D-J2cjak.js";
import { c as ye } from "./check-C9mY6LiX.js";
import { _ as be } from "./PageLayout.vue_vue_type_script_setup_true_lang-2f0QfweQ.js";
import { u as ke } from "./search-BAPEUu1R.js";
import { u as xe } from "./app-DhRTGWa_.js";
import { c as Se } from "./createComponentProgrammatically-Bt2rn1IQ.js";
const Ce = { class: "fm-typo-en-title-md-600" }, qe = { class: "space-y-32 flex flex-col h-full" }, Ee = { class: "flex gap-8 items-center justify-start" }, Ve = /* @__PURE__ */ H({
  __name: "Form",
  props: {
    action: {},
    initialValue: {}
  },
  emits: ["submitted"],
  setup(K, { expose: b, emit: N }) {
    const { t: r } = ee(), p = K, R = N, s = I(
      p.initialValue ? Q(p.initialValue) : {
        _id: "",
        name: "",
        position: 0,
        items: []
      }
    ), C = W(), i = ne(), D = X(i), q = Z(D), c = I(!1), u = I(!1), _ = (f) => {
      ye.isBoolean(f) ? u.value = f : u.value = !u.value;
    }, E = L(() => p.action === "add" ? r("menu.serving_sequence.add") : r("menu.serving_sequence.update"));
    async function P() {
      try {
        if (p.action === "add")
          await q.updateMenu(
            {
              module: S.F_MENU_MODULE_V4_KEY.enum.serveSequence,
              operation: O.F_OPERATION_TYPE.create,
              data: {
                ...s.value,
                position: C.serveSequence.length
              }
            },
            s.value.name
          );
        else if (p.action === "update")
          await q.updateMenu(
            {
              module: S.F_MENU_MODULE_V4_KEY.enum.serveSequence,
              operation: O.F_OPERATION_TYPE.update,
              data: s.value
            },
            s.value.name
          );
        else
          throw new Error("Invalid action");
      } finally {
        u.value = !1, R("submitted");
      }
    }
    b({
      trigger: _,
      show: u
    });
    function U(f) {
      return f.reduce((a, v) => (a[v._id] = [...a[v._id] ?? [], v], a), {});
    }
    const B = L(() => U(Q(s.value.items)));
    return (f, a) => {
      const v = h("fm-text-field"), V = h("fm-button"), e = h("fm-side-sheet");
      return d(), g(x, null, [
        ae(f.$slots, "default", { trigger: _ }),
        l(e, {
          id: "group-form",
          modelValue: u.value,
          "onUpdate:modelValue": a[3] || (a[3] = (n) => u.value = n),
          "is-container": t(Y).FmForm,
          "is-container-props": {
            onValidationSuccess: P,
            blameFormChildOnValidationFailed: !0
          },
          "max-width": 560
        }, {
          "side-sheet-header": m(() => [
            y("p", Ce, z(E.value), 1)
          ]),
          "side-sheet-footer": m(() => [
            y("div", Ee, [
              l(V, {
                label: t(r)(p.action === "add" ? "menu.serving_sequence.add" : "menu.serving_sequence.update"),
                loading: c.value,
                size: "lg",
                type: "submit",
                variant: "primary"
              }, null, 8, ["label", "loading"]),
              l(V, {
                label: t(r)("menu.common.actions.cancel"),
                size: "lg",
                variant: "tertiary",
                onClick: a[2] || (a[2] = () => u.value = !1)
              }, null, 8, ["label"])
            ])
          ]),
          default: m(() => [
            y("div", qe, [
              l(v, {
                autofocus: "",
                modelValue: s.value.name,
                "onUpdate:modelValue": a[0] || (a[0] = (n) => s.value.name = n),
                rules: [
                  (n) => !!n || t(r)("menu.common.validation.required", {
                    field: t(r)("menu.serving_sequence.columns.name").toLowerCase()
                  })
                ],
                label: t(r)("menu.serving_sequence.columns.name"),
                placeholder: t(r)("menu.common.labels.enter_name")
              }, null, 8, ["modelValue", "rules", "label", "placeholder"]),
              l(t(me), {
                "categorized-items": t(C).categorizedItems,
                data: B.value,
                class: "flex-1",
                "select-variant": "",
                "show-variant": "",
                "onUpdate:data": a[1] || (a[1] = (n) => s.value.items = Object.values(n).flatMap((k) => k))
              }, null, 8, ["categorized-items", "data"])
            ])
          ]),
          _: 1
        }, 8, ["modelValue", "is-container", "is-container-props"])
      ], 64);
    };
  }
}), T = Ve, we = {
  key: 0,
  class: "xs:pt-24"
}, Me = {
  class: "flex justify-end mb-8 xs:mt-8"
}, Fe = {
  key: 1,
  class: /* @__PURE__ */ J(["flex-1", "overflow-scroll", "divide-y divide-fm-color-neutral-gray-100", "pb-64"])
}, Ie = ["onClick"], Le = {
  class: "flex-1 space-y-4"
}, Oe = {
  class: "fm-typo-en-body-lg-600"
}, Ne = {
  class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary"
}, Qe = /* @__PURE__ */ H({
  __name: "ServingSequence",
  setup(K) {
    const {
      searchKey: b,
      filter: N
    } = ke(), r = W(), p = ne(), R = X(p), s = Z(R), C = _e(), i = pe(), D = xe(), q = ce(), {
      t: c
    } = ee(), u = (e) => {
      e && e !== S.F_MENU_VERSION.enum.v4 && q.push({
        name: he.CATALOG
      });
    };
    oe(() => {
      var e;
      u((e = i.currentBusiness.value) == null ? void 0 : e.menuVersion);
    }), F(() => {
      var e;
      return (e = i.currentBusiness.value) == null ? void 0 : e.menuVersion;
    }, (e) => {
      u(e);
    }), F(() => i.sessionUser.value, (e) => {
      e && D.getPublicSetting();
    }), F(() => i.currentBusiness.value, async (e, n) => {
      e && e._id !== (n == null ? void 0 : n._id) && await r.readRestaurants();
    }), F(() => i.currentRestaurant.value, async (e, n) => {
      e && e._id !== (n == null ? void 0 : n._id) && await r.readMenu();
    }), se(() => {
      i.restaurants.value.length && (i.currentRestaurant.value || i.changeRestaurant(i.restaurants.value[0]));
    });
    const _ = L(() => r.serveSequence.filter(({
      name: e
    }) => N([e])) ?? []);
    function E(e) {
      C.open({
        title: "Delete sequence",
        message: `Are you sure to delete sequence ${e.name} ?`,
        primaryActions: {
          text: "Delete",
          close: !0,
          variant: A.Destructive
        },
        secondaryActions: {
          text: "Cancel",
          close: !0
        }
      }).onPrimary(async () => {
        await s.updateMenu({
          module: S.F_MENU_MODULE_V4_KEY.enum.serveSequence,
          operation: O.F_OPERATION_TYPE.delete,
          data: e._id
        }, e.name, !0);
      });
    }
    const P = ({
      servingSequence: e
    }) => $(Y.FmButton, {
      prependIcon: "delete",
      variant: A.Tertiary,
      textColor: "neutral-gray-400",
      onClick: (n) => {
        n.stopPropagation(), E(e);
      }
    });
    async function U(e) {
      await s.updateMenu({
        module: S.F_MENU_MODULE_V4_KEY.enum.serveSequence,
        operation: O.F_OPERATION_TYPE.rearrange,
        data: e.map((n) => n._id)
      }, "sequences");
    }
    const B = I([{
      accessorKey: "name",
      header: () => c("menu.serving_sequence.columns.name"),
      enableSorting: !1,
      size: 360
    }, {
      accessorKey: "items",
      header: "Product linked",
      enableSorting: !1,
      cell: (e) => `${e.getValue().length} items linked`
    }, {
      id: "action",
      size: 52,
      meta: {
        cellClass: "pl-16",
        headerContentClass: "-mx-16"
      },
      header: "",
      cell: (e) => $("div", {
        class: "w-full flex justify-end items-center"
      }, [$(Y.FmButton, {
        prependIcon: "delete",
        variant: A.Tertiary,
        textColor: "neutral-gray-400",
        onClick: (n) => {
          n.stopPropagation(), E(e.row.original);
        }
      })])
    }]), f = le();
    function a(e) {
      var w, M;
      const {
        container: n,
        vNode: k
      } = Se(T, f, {
        initialValue: e,
        action: "update",
        onSubmitted: () => {
          n == null || n.remove();
        }
      });
      (M = (w = k.component) == null ? void 0 : w.exposed) == null || M.trigger();
    }
    re(() => r.selectCatalog(null));
    const v = fe(), V = L(() => v.breakpoints.value.xs);
    return (e, n) => {
      const k = h("FmSpacer"), w = h("fm-button"), M = h("fm-search"), te = h("fm-table");
      return d(), j(be, {
        class: "max-h-full",
        heading: t(c)("menu.serving_sequence.title")
      }, {
        "append-heading": m(() => [!t(s).checkMenuIsLoading() && _.value.length ? (d(), g(x, {
          key: 0
        }, [l(k), l(t(T), {
          action: "add"
        }, {
          default: m(({
            trigger: o
          }) => [l(ge, {
            class: "ml-auto",
            label: t(c)("menu.serving_sequence.add"),
            "prepend-icon": "add",
            onClick: o
          }, null, 8, ["label", "onClick"])]),
          _: 1
        })], 64)) : G("", !0)]),
        default: m(() => [t(s).checkMenuIsLoading() ? G("", !0) : (d(), g(x, {
          key: 0
        }, [_.value.length ? (d(), g(x, {
          key: 1
        }, [y("div", Me, [l(M, {
          autofocus: "",
          modelValue: t(b),
          "onUpdate:modelValue": n[0] || (n[0] = (o) => ie(b) ? b.value = o : null),
          placeholder: t(c)("menu.common.labels.search_placeholder", {
            type: "sequences"
          }),
          class: "w-[320px] xs:w-full xs:px-16"
        }, null, 8, ["modelValue", "placeholder"])]), V.value ? (d(), g("div", Fe, [(d(!0), g(x, null, ue(_.value, (o) => (d(), g("div", {
          key: o._id,
          class: J(["py-12 px-16", "flex items-center space-x-8"]),
          onClick: (Re) => a(o)
        }, [y("div", Le, [y("p", Oe, z(o.name), 1), y("p", Ne, z(t(c)("menu.common.labels.products_linked", {
          count: o.items.length
        })), 1)]), l(P, {
          servingSequence: o
        }, null, 8, ["servingSequence"])], 8, Ie))), 128))])) : (d(), j(ve, {
          key: 0
        }, {
          default: m(() => [l(te, {
            "column-defs": B.value,
            loading: t(s).checkMenuIsLoading(),
            "page-size": _.value.length,
            "row-data": _.value,
            "search-value": t(b),
            "shrink-at": !1,
            class: "flex-1 overflow-hidden",
            draggable: "",
            "hide-footer": "",
            "pin-header-row": "",
            onDndChanged: n[1] || (n[1] = (o) => U(o)),
            onRowClick: n[2] || (n[2] = (o) => a(o.original))
          }, null, 8, ["column-defs", "loading", "page-size", "row-data", "search-value"])]),
          _: 1
        }))], 64)) : (d(), g("div", we, [l(t(de), {
          subtitle: t(c)("menu.serving_sequence.empty.subtitle"),
          title: t(c)("menu.serving_sequence.empty.title")
        }, {
          action: m(() => [l(t(T), {
            action: "add"
          }, {
            default: m(({
              trigger: o
            }) => [l(w, {
              label: t(c)("menu.serving_sequence.add"),
              "prepend-icon": "add",
              onClick: o
            }, null, 8, ["label", "onClick"])]),
            _: 1
          })]),
          _: 1
        }, 8, ["subtitle", "title"])]))], 64))]),
        _: 1
      }, 8, ["heading"]);
    };
  }
});
export {
  Qe as default
};
