import { defineComponent as q, ref as f, computed as r, watch as G, h as i, resolveComponent as x, openBlock as B, createElementBlock as H, createElementVNode as b, toDisplayString as J, createVNode as y, createBlock as O, createCommentVNode as Q, unref as V } from "vue";
import { useCoreStore as W, useI18n as X } from "@feedmepos/mf-common";
import { useSnackbar as Y, components as A } from "@feedmepos/ui-library";
import { K as Z, D as ee } from "./app-DiX-EfV6.js";
import { u as le } from "./app-Bpb4394e.js";
import { F as te } from "./FmAdminBadge-DjnBAgyv.js";
const ae = {
  class: "flex flex-col gap-24 h-full",
  style: { "max-height": "50vh" }
}, oe = { class: "flex items-center flex-shrink-0" }, ne = { class: "fm-typo-en-body-lg-600 flex-1" }, se = { class: "flex gap-8" }, ie = { class: "flex flex-col gap-4 w-full flex-1 min-h-0" }, re = { class: "flex items-center gap-8 flex-shrink-0" }, ue = { class: "flex-1 border border-fm-color-border-secondary rounded-lg overflow-hidden overflow-y-auto min-h-0" }, he = /* @__PURE__ */ q({
  __name: "TemplatePublishDialog",
  props: {
    title: {},
    doc: {},
    controller: {},
    initialPublishedRev: {},
    locations: {},
    enabledLocations: {},
    hideUnpublish: { type: Boolean }
  },
  setup(U) {
    const s = U, p = f(s.initialPublishedRev ?? {}), t = f(), n = f(/* @__PURE__ */ new Set()), C = le(), $ = W(), k = Y(), E = r(() => {
      var e;
      return ((e = $.sessionUser.value) == null ? void 0 : e.role.isAdmin) ?? !1;
    }), S = r(() => {
      var l;
      return ((l = s.enabledLocations) != null && l.length ? s.enabledLocations : s.locations).map((a) => {
        var o;
        if (!!!C.locationByDbName[a.dbName])
          return {
            ...a,
            status: "invalid"
          };
        const v = !!(((o = p.value) == null ? void 0 : o[a.dbName]) ?? []).find(
          (_) => _._id === s.doc._id && (_.updatedAt ? _.updatedAt === s.doc.updatedAt : _._rev === s.doc._rev)
        );
        return {
          ...a,
          status: v ? "published" : "outdated",
          state: a.doc.profile.address.state
        };
      });
    }), { t: m } = X(), g = f(""), w = f({
      logic: "AND",
      rules: []
    }), D = [
      {
        type: "string",
        key: "status",
        entity: "inventory",
        values: ["published", "outdated"]
      },
      {
        type: "string",
        key: "state",
        entity: "inventory",
        values: [
          ...new Set(C.locations.map((e) => e.doc.profile.address.state).filter(Boolean))
        ]
      }
    ], u = r(() => {
      const e = g.value.toLowerCase();
      return S.value.filter((l) => Z(l, w.value)).filter(({ name: l, dbName: a }) => !!(!e || l.toLowerCase().includes(e) || E.value && a.toLowerCase().includes(e)));
    }), N = r(
      () => u.value.filter((e) => e.status !== "invalid")
    );
    G(
      [g, w],
      () => {
        n.value = /* @__PURE__ */ new Set();
      },
      { deep: !0 }
    );
    const F = r(() => u.value.length === 0 ? !1 : u.value.every((e) => n.value.has(e.dbName))), T = r(() => {
      if (N.value.length === 0) return !1;
      const e = N.value.filter(
        (l) => n.value.has(l.dbName)
      ).length;
      return e > 0 && e < N.value.length;
    });
    function z() {
      F.value ? u.value.forEach((e) => n.value.delete(e.dbName)) : u.value.forEach((e) => n.value.add(e.dbName)), n.value = new Set(n.value);
    }
    function P(e) {
      e.status !== "invalid" && (n.value.has(e.dbName) ? n.value.delete(e.dbName) : n.value.add(e.dbName), n.value = new Set(n.value));
    }
    function L() {
      const e = u.value.filter(
        (l) => l.status !== "invalid" && n.value.has(l.dbName)
      );
      return e.length === 0 ? N.value : e;
    }
    const R = r(() => [
      {
        id: "checkbox",
        header: () => "",
        size: 56,
        cell: (e) => {
          const l = e.row.original;
          return l.status === "invalid" ? i("div", { class: "w-56" }) : i(A.FmCheckbox, {
            value: l.dbName,
            modelValue: n.value.has(l.dbName),
            "onUpdate:modelValue": () => P(l)
          });
        }
      },
      {
        id: "name",
        header: () => "Name",
        size: "auto",
        cell: (e) => {
          const l = e.row.original;
          return i("div", { class: "flex flex-col" }, [
            i("span", {}, l.name),
            i(
              te,
              {},
              {
                default: () => i("div", { class: "flex items-center gap-4" }, [
                  i(
                    "span",
                    { class: "fm-typo-en-body-sm-400 text-fm-color-typo-tertiary" },
                    l.dbName
                  ),
                  i(A.FmButton, {
                    variant: "tertiary",
                    icon: "content_copy",
                    size: "sm",
                    onClick: async (a) => {
                      a.stopPropagation();
                      try {
                        await navigator.clipboard.writeText(l.dbName), k == null || k.open({
                          title: "Copied to clipboard",
                          message: l.name,
                          type: "success"
                        });
                      } catch (h) {
                        console.error("Failed to copy:", h);
                      }
                    }
                  })
                ])
              }
            )
          ]);
        }
      },
      {
        id: "status",
        header: () => "Status",
        size: 200,
        cell: (e) => {
          const l = e.row.original, a = l.status === "published";
          if (l.status === "invalid")
            return i(
              "div",
              {
                class: ["fm-status-badge", "fm-status-badge-error-secondary"]
              },
              "Invalid"
            );
          let c;
          a && s.controller.unpublishAtLocation && !s.hideUnpublish ? c = i(A.FmButton, {
            variant: "tertiary",
            icon: "block",
            loading: t.value === `unpublish-${l.dbName}`,
            disabled: t.value !== void 0 && t.value !== `unpublish-${l.dbName}`,
            onClick: async () => {
              t.value = `unpublish-${l.dbName}`;
              try {
                const o = await s.controller.unpublishAtLocation(l).delayed(1e3);
                p.value = o;
              } catch (o) {
                console.error("Error unpublishing at location:", o);
              } finally {
                t.value = void 0;
              }
            }
          }) : a || (c = i(A.FmButton, {
            variant: "tertiary",
            icon: "ios_share",
            loading: t.value === `publish-${l.dbName}`,
            disabled: t.value !== void 0 && t.value !== `publish-${l.dbName}`,
            onClick: async () => {
              t.value = `publish-${l.dbName}`;
              try {
                const o = await s.controller.publishAtLocation(l).delayed(1e3);
                p.value = o;
              } catch (o) {
                console.error("Error publishing at location:", o);
              } finally {
                t.value = void 0;
              }
            }
          }));
          const v = [
            i(
              "div",
              {
                class: [
                  "fm-status-badge",
                  a ? "fm-status-badge-success-secondary" : "fm-status-badge-info-secondary"
                ]
              },
              m(a ? "inventory.publish.status.published" : "inventory.publish.status.outdated")
            )
          ];
          return c && v.push(c), i("div", { class: "flex items-center gap-8" }, v);
        }
      }
    ]);
    async function I() {
      t.value = "all";
      try {
        const e = L(), l = await s.controller.publishAll(e).delayed(1e3);
        p.value = l;
      } catch (e) {
        console.error("Error publishing all:", e);
      } finally {
        t.value = void 0;
      }
    }
    async function K() {
      if (s.controller.unpublishAll) {
        t.value = "unpublish-all";
        try {
          const e = L(), l = await s.controller.unpublishAll(e).delayed(1e3);
          p.value = l;
        } catch (e) {
          console.error("Error unpublishing all:", e);
        } finally {
          t.value = void 0;
        }
      }
    }
    const d = r(() => n.value.size), M = r(() => d.value === 0 || d.value === S.value.length ? m("inventory.publish.actions.publishAll") : m("inventory.publish.actions.publishSelected", { count: d.value })), j = r(() => d.value === 0 || d.value === S.value.length ? "Unpublish all" : `Unpublish selected ${d.value} location${d.value === 1 ? "" : "s"}`);
    return (e, l) => {
      const a = x("FmButton"), h = x("FmTextField"), c = x("FmCheckbox"), v = x("FmTable");
      return B(), H("div", ae, [
        b("div", oe, [
          b("div", ne, J(e.title), 1),
          b("div", se, [
            y(a, {
              label: M.value,
              variant: "secondary",
              onClick: l[0] || (l[0] = (o) => I()),
              loading: t.value === "all",
              disabled: t.value !== "all" && t.value !== void 0
            }, null, 8, ["label", "loading", "disabled"]),
            e.controller.unpublishAll && !e.hideUnpublish ? (B(), O(a, {
              key: 0,
              label: j.value,
              variant: "tertiary",
              onClick: l[1] || (l[1] = (o) => K()),
              loading: t.value === "unpublish-all",
              disabled: t.value !== "unpublish-all" && t.value !== void 0
            }, null, 8, ["label", "loading", "disabled"])) : Q("", !0)
          ])
        ]),
        b("div", ie, [
          y(h, {
            modelValue: g.value,
            "onUpdate:modelValue": l[2] || (l[2] = (o) => g.value = o),
            class: "w-full flex-shrink-0",
            placeholder: V(m)("inventory.publish.search.placeholder"),
            "prepend-icon": "search"
          }, null, 8, ["modelValue", "placeholder"]),
          b("div", re, [
            y(V(ee), {
              modelValue: w.value,
              "onUpdate:modelValue": l[3] || (l[3] = (o) => w.value = o),
              attributes: D
            }, null, 8, ["modelValue"]),
            y(c, {
              value: "select-all",
              "model-value": F.value,
              indeterminate: T.value,
              "onUpdate:modelValue": z,
              label: "Select all"
            }, null, 8, ["model-value", "indeterminate"])
          ]),
          b("div", ue, [
            y(v, {
              "row-data": u.value,
              "column-defs": R.value,
              "shrink-at": 9999,
              virtual: !0,
              "page-size": u.value.length,
              "hide-footer": ""
            }, null, 8, ["row-data", "column-defs", "page-size"])
          ])
        ])
      ]);
    };
  }
});
export {
  he as _
};
