import { defineComponent as R, computed as W, ref as oe, watch as q, resolveComponent as b, createElementBlock as f, openBlock as u, renderSlot as re, Fragment as D, renderList as U, createBlock as g, unref as r, withCtx as C, createElementVNode as L, createCommentVNode as N, createVNode as p, isRef as S, useModel as ue, normalizeClass as z, toDisplayString as ie } from "vue";
import { u as me, b as H, d as E, j as de } from "./vue-i18n-DG0DIzwC.js";
import { storeToRefs as T } from "pinia";
import { a as pe, d as ce } from "./NavigationTab.vue_vue_type_script_setup_true_lang-EbtoF2G2.js";
import { _ as J, a as fe } from "./DateRangeSelect.vue_vue_type_script_setup_true_lang-DPMsvMfX.js";
import { a as ve, b as be, D as w, q as _e, W as Y, S as ye } from "./BaseDialog.vue_vue_type_script_setup_true_lang-BqtS2XG4.js";
import { _ as he } from "./NoData.vue_vue_type_script_setup_true_lang-j8BlZPPp.js";
import { d as ge } from "./helper-C0VLdBRU.js";
import { detectLocale as Fe } from "@feedmepos/mf-common";
import { useBreakpoints as ke } from "@feedmepos/ui-library";
const xe = { class: "flex flex-wrap gap-2" }, we = { class: "flex flex-col gap-1 p-2 bg-fm-color-neutral-white max-h-[300px] overflow-y-auto relative fm-shadow-light-300" }, Ce = {
  key: 0,
  class: "flex justify-center my-2"
}, Se = /* @__PURE__ */ R({
  __name: "FilterSelector",
  setup(I) {
    var G;
    const { t: v } = me(), { currentReport: m } = T(ve());
    let { globalFilters: F, isGlobalFiltersLoading: i, timeRange: _, dateRange: y, selectedLocationIds: h } = T(H()), { schemas: $ } = T(be());
    const n = W(() => {
      var e;
      return ((e = m.value) == null ? void 0 : e.id) ?? "";
    }), o = oe([]);
    q(
      ((G = m.value) == null ? void 0 : G.globalFilters) || [],
      () => {
        o.value = F.value.map((e) => ({
          filter: e,
          search: "",
          options: [],
          type: K(e)
        }));
      },
      { deep: !0, immediate: !0 }
    ), q(
      [_, y, h],
      async () => {
        await te();
      },
      { deep: !0, immediate: !0 }
    );
    var k = void 0;
    function K(e) {
      var l;
      const t = (l = $.value.find((a) => a.name === e.schemaName)) == null ? void 0 : l.fields.find((a) => a.name === e.name);
      return t == null ? void 0 : t.type;
    }
    function Q(e) {
      return {
        type: Y.Table,
        config: {
          schemaNames: Array.from(
            /* @__PURE__ */ new Set([e.schemaName, ...(e.filters ?? []).map((t) => t.schemaName)])
          ),
          dimensions: [
            {
              name: e.name ?? "",
              schemaName: e.schemaName ?? "",
              label: e.name ?? "",
              hide: !1,
              option: null
            }
          ],
          rowIds: [],
          metrics: [],
          filters: e.filters || [],
          sorts: [
            {
              name: e.name ?? "",
              schemaName: e.schemaName ?? "",
              type: ye.Asc,
              aggregation: null,
              dimensionOption: null
            }
          ],
          joinDatasources: [],
          limit: null,
          rollup: void 0,
          drillDimension: void 0,
          showGrandTotal: !1,
          breakdownDimension: void 0,
          sparklineDimension: void 0,
          isTransposed: !1,
          isDrillable: !1
        },
        title: ""
      };
    }
    function V(e) {
      return e.options.every((t) => {
        var l;
        return (l = e.filter.values) == null ? void 0 : l.includes(t.value);
      });
    }
    function X(e) {
      V(e) ? e.filter.values = ["NULL"] : e.filter.values = e.options.map((t) => t.value);
    }
    const Z = W(
      () => o.value.map((e) => {
        const t = e.options, l = e.search.toLowerCase() ?? "";
        return t.filter((a) => a.label.toLowerCase().includes(l.toLowerCase()));
      })
    );
    async function ee(e) {
      switch (e.type) {
        case w.String:
        case w.Numeric:
          {
            const t = await _e(
              Q(e.filter),
              k.signal
            ), l = (t == null ? void 0 : t.type) === Y.Table ? t.rows.map((a) => {
              var d;
              return ((d = a.cells) == null ? void 0 : d[0]) ?? "";
            }) : [];
            e.options = l.map((a) => ({
              label: a,
              value: a
            })), e.filter.values = l.length ? l : ["NULL"];
          }
          break;
        case w.Bool:
          e.options = [
            { label: "Yes", value: !0 },
            { label: "No", value: !1 }
          ], e.filter.values = [!0, !1];
          break;
        case w.Timestamp:
          break;
      }
    }
    async function te() {
      if (!(!n.value || !o.value.length)) {
        k && (k == null || k.abort()), k = new AbortController();
        try {
          i.value = !0;
          const e = o.value.map(async (t) => {
            await ee(t);
          });
          await Promise.all(e);
        } finally {
          i.value = !1;
        }
      }
    }
    function le(e, t) {
      var a, d;
      if ((a = e.filter.values) == null ? void 0 : a.includes(t)) {
        let x = (e.filter.values || []).filter((s) => s !== t);
        x.length === 0 && (x = ["NULL"]), e.filter.values = x;
      } else
        (d = e.filter.values) == null || d.push(t);
    }
    function M(e, t) {
      if (t === null)
        e.values = [];
      else {
        const l = E(t.startDate).startOf("day").utc().toISOString(), a = E(t.endDate).endOf("day").utc().toISOString();
        e.values = [l, a];
      }
    }
    function ae(e) {
      var l;
      const t = (l = e.filter.values) == null ? void 0 : l.filter((a) => a !== "NULL");
      return `${v("report.section.filter.selectAll")} (${t == null ? void 0 : t.length}/${e.options.length})`;
    }
    function se(e) {
      const t = e.options.length, l = v("report.section.filter.search"), a = v("report.common.results", { count: t });
      return `${l} (${a})`;
    }
    function O(e) {
      var l, a, d;
      const t = de(e.filter);
      switch (e.type) {
        case w.Timestamp:
          return ((l = e.filter.values) == null ? void 0 : l.length) === 2 ? `${t} is between ${ge({
            startDate: (a = e.filter.values) == null ? void 0 : a[0],
            endDate: (d = e.filter.values) == null ? void 0 : d[1],
            locale: Fe()
          })}` : t;
        default:
          return t;
      }
    }
    return (e, t) => {
      const l = b("FmCircularProgress"), a = b("FmTextField"), d = b("FmMenuItem"), x = b("FmMenu");
      return u(), f("div", xe, [
        (u(!0), f(D, null, U(o.value, (s, ne) => {
          var A, B, j;
          return u(), f("div", {
            key: `${s.filter.schemaName}-${s.filter.name}`
          }, [
            s.type === r(w).Timestamp ? (u(), g(J, {
              key: 0,
              "model-value": { startDate: (A = s.filter.values) == null ? void 0 : A[0], endDate: (B = s.filter.values) == null ? void 0 : B[1] },
              class: "w-full",
              label: O(s),
              removable: ((j = s.filter.values) == null ? void 0 : j.length) === 2,
              onUpdate: (c) => M(s.filter, c),
              onChipClosed: () => M(s.filter, null)
            }, null, 8, ["model-value", "label", "removable", "onUpdate", "onChipClosed"])) : (u(), g(x, {
              key: 1,
              "close-on-click": !1,
              shift: !0
            }, {
              "menu-button": C(() => [
                p(fe, {
                  "left-icon": "filter_alt",
                  "right-icon": "expand_more",
                  label: O(s)
                }, null, 8, ["label"])
              ]),
              "menu-wrapper": C(() => [
                L("div", we, [
                  r(i) ? (u(), f("div", Ce, [
                    p(l)
                  ])) : N("", !0),
                  s.options.length > 0 && !r(i) ? (u(), f(D, { key: 1 }, [
                    p(a, {
                      modelValue: s.search,
                      "onUpdate:modelValue": (c) => s.search = c,
                      type: "text",
                      "prepend-icon": "search",
                      placeholder: se(s),
                      class: "border px-2 py-1 text-sm mb-1 rounded"
                    }, null, 8, ["modelValue", "onUpdate:modelValue", "placeholder"]),
                    p(d, {
                      label: ae(s),
                      "has-checkbox": !0,
                      "model-value": V(s),
                      indeterminate: !0,
                      onClick: (c) => X(s)
                    }, null, 8, ["label", "model-value", "onClick"]),
                    (u(!0), f(D, null, U(Z.value[ne], (c) => {
                      var P;
                      return u(), g(d, {
                        key: c.value,
                        label: c.label,
                        "has-checkbox": !0,
                        "model-value": (P = s.filter.values) == null ? void 0 : P.includes(c.value),
                        onClick: () => le(s, c.value)
                      }, null, 8, ["label", "model-value", "onClick"]);
                    }), 128))
                  ], 64)) : r(i) ? N("", !0) : (u(), g(he, { key: 2 }))
                ])
              ]),
              _: 2
            }, 1024))
          ]);
        }), 128)),
        re(e.$slots, "default")
      ]);
    };
  }
}), $e = { class: "flex flex-col gap-2 overflow-x-auto overflow-y-hidden scrollbar-hide" }, De = { class: "flex flex-col gap-2 py-2" }, Te = /* @__PURE__ */ R({
  __name: "Filter",
  setup(I) {
    const {
      locations: v,
      selectedLocationIds: m,
      dateRange: F,
      compareDateRange: i,
      timeRange: _,
      defaultDateSetting: y,
      selectTimeDefault: h
    } = T(H());
    return ($, n) => (u(), f("div", $e, [
      L("div", De, [
        p(pe, {
          modelValue: r(m),
          "onUpdate:modelValue": n[5] || (n[5] = (o) => S(m) ? m.value = o : null),
          options: r(v)
        }, {
          default: C(() => [
            p(J, {
              "date-range": r(F),
              "onUpdate:dateRange": n[0] || (n[0] = (o) => S(F) ? F.value = o : null),
              "compare-date-range": r(i),
              "onUpdate:compareDateRange": n[1] || (n[1] = (o) => S(i) ? i.value = o : null),
              "compare-type": r(y).defaultCompareType,
              "onUpdate:compareType": n[2] || (n[2] = (o) => r(y).defaultCompareType = o),
              compare: ""
            }, null, 8, ["date-range", "compare-date-range", "compare-type"]),
            p(ce, {
              "time-range": r(_),
              "onUpdate:timeRange": n[3] || (n[3] = (o) => S(_) ? _.value = o : null),
              "select-time-default": r(h),
              "onUpdate:selectTimeDefault": n[4] || (n[4] = (o) => S(h) ? h.value = o : null),
              "default-date-range": r(y).timeOptions
            }, null, 8, ["time-range", "select-time-default", "default-date-range"]),
            p(Se)
          ]),
          _: 1
        }, 8, ["modelValue", "options"])
      ])
    ]));
  }
}), Le = { class: "fm-typo-en-body-md-400" }, je = /* @__PURE__ */ R({
  __name: "MenuTab",
  props: {
    modelValue: { required: !1, default: [] },
    modelModifiers: {}
  },
  emits: ["update:modelValue"],
  setup(I) {
    const v = ue(I, "modelValue"), { breakpoints: m } = ke();
    return (F, i) => {
      const _ = b("FmButton"), y = b("FmIcon"), h = b("FmMenuItem"), $ = b("FmMenu");
      return u(), f("div", {
        class: z(["flex items-start pb-2 px-24", `${r(m).lg || r(m).md ? "px-24" : "pl-3"}`])
      }, [
        p(Te),
        i[0] || (i[0] = L("div", { class: "flex grow" }, null, -1)),
        v.value.length > 0 ? (u(), g($, {
          key: 0,
          trigger: "click",
          placement: "left",
          shift: !0,
          class: z(r(m).sm || r(m).xs ? "pr-3" : "")
        }, {
          "menu-button": C(() => [
            p(_, {
              "append-icon": "more_vert",
              variant: "tertiary",
              size: "md",
              class: "w-[36px] bg-none"
            })
          ]),
          default: C(() => [
            (u(!0), f(D, null, U(v.value, (n, o) => (u(), g(h, {
              key: `button-${o}`,
              onClick: n.onClick
            }, {
              label: C(() => [
                n.prependIcon ?? !1 ? (u(), g(y, {
                  key: 0,
                  name: n.icon
                }, null, 8, ["name"])) : N("", !0),
                L("p", Le, ie(n.label), 1)
              ]),
              _: 2
            }, 1032, ["onClick"]))), 128))
          ]),
          _: 1
        }, 8, ["class"])) : N("", !0)
      ], 2);
    };
  }
});
export {
  je as _
};
