import { jsxs as M, jsx as f, Fragment as ye } from "@emotion/react/jsx-runtime";
import { useEnvironment as ve, useModuleDictionary as De } from "@m4l/core";
import { useState as S, useRef as w, useMemo as m, useCallback as a, useReducer as Te } from "react";
import { DynamicFilter as Ae } from "../../components/DynamicFilter/DynamicFilter.js";
import { DynamicSort as Ie } from "../../components/DynamicSort/DynamicSort.js";
import { ToggleIconButton as se } from "../../components/extended/mui/ToggleIconButton/ToggleIconButton.js";
import { getPropDataTestId as H } from "../../test/getNameDataTestId.js";
import { COOKIE_APPLIED_FILTERS as x, COOKIE_APPLIED_SORTS as E, M4LDYNAMIC_KEY_FILTER_AND_SORT as N } from "./constants.js";
import { ICON_PATH_FILTER as _e, ICON_PATH_SORT as be, ASSETS as Re } from "./icons.js";
import { DynamicFilterAndSortSlots as V } from "./slots/DynamicFilterAndSortEnum.js";
import { StackLeftActionsStyled as ke, StackRightActionsStyled as we, ActionRefreshStyled as le, StackCustomHeaderStyled as xe } from "./slots/DynamicFilterAndSortSlots.js";
import { deepEqual as ae } from "fast-equals";
import { getPurgedCookie as ce } from "./helpers.js";
import { useWindowToolsMF as Ee } from "../../components/WindowBase/hooks/useWindowToolsMF/index.js";
import { DICCTIONARY as $e } from "../../components/DynamicFilter/dictionary.js";
const Ge = (ue) => {
  const {
    fields: o,
    sorts: r,
    onChangeFilterSort: d,
    dataTestId: g,
    withAllField: B,
    rightActions: Y,
    initialFilterToggleed: fe = !0,
    initialSortToggleed: me = !0,
    prefixCookie: s,
    setCookie: p,
    getCookie: j,
    filterSortAutomatic: u = !0,
    visibleRefresh: $ = !1,
    withExternalRefresh: q
  } = ue, { host_static_assets: C, environment_assets: F } = ve(), [c, y] = S(() => ({
    filter: fe,
    sort: me
  })), [v] = S(() => ce(
    j?.(
      s ? `${s}_${x}` : x
    )
  )), [D] = S(() => ce(
    j?.(
      s ? `${s}_${E}` : E
    )
  )), T = w(0), l = w(null), i = w(null), [A, O] = S(!1), [I, P] = S(!1), { toast: U } = Ee(), { getLabel: W } = De(), [L, _] = S(() => ({
    filter: v?.length === 0,
    sort: D?.length === 0
  })), de = m(
    () => c.filter || c.sort,
    [c]
  ), b = `${C}/${F}/${Re.refresh}`, n = w({
    eventFilters: { filters: v, rawFilters: [] },
    eventSorts: { sorts: D, rawSorts: [] }
  }), z = (e) => {
    y((t) => ({ ...t, [e]: !t[e] }));
  }, R = a(() => {
    if (o.some((e) => e.presence === "fixed")) {
      const e = n.current?.eventFilters?.filters;
      return !(!e || e.length === 0);
    }
    return !0;
  }, [n, o]), [G, J] = Te(
    (e, t) => ({ ...e, [t]: !e[t] }),
    { filters: !1, sorts: !1 }
  ), Q = a(() => {
    O(!0);
  }, [O]), X = a(
    (e, t) => {
      _((h) => ({ ...h, filter: e.length === 0 })), n.current?.eventFilters?.filters && !ae(n.current?.eventFilters?.filters, e) && p?.(
        s ? `${s}_${x}` : x,
        "window",
        e
      ), n.current = {
        ...n.current,
        eventFilters: { filters: e, rawFilters: t }
      }, (T.current > 0 || T.current === 0 && !r) && d(n.current), T.current++, J("filters"), O(!1);
    },
    [d, s, p, _, r]
  ), Z = a(() => {
    P(!0);
  }, [P]), ee = a(
    (e, t) => {
      _((h) => ({ ...h, sort: e.length === 0 })), n.current?.eventSorts?.sorts && !ae(n.current?.eventSorts?.sorts, e) && p?.(
        s ? `${s}_${E}` : E,
        "window",
        e
      ), n.current = {
        ...n.current,
        eventSorts: { sorts: e, rawSorts: t }
      }, R() ? d(n.current) : T.current++, P(!1), J("sorts");
    },
    [
      d,
      s,
      p,
      _,
      R
    ]
  ), k = a(() => {
    u ? R() ? d(n.current) : U(
      { title: W($e.error_invalid_filters_before) },
      { type: "error" }
    ) : (l.current && l.current.fireOnChangeFilter(), i.current && i.current.fireOnChangeSort());
  }, [
    u,
    W,
    R,
    d,
    U
  ]), ge = m(
    () => /* @__PURE__ */ M(
      ke,
      {
        direction: "row",
        ...H(
          N,
          V.stackLeftActions,
          g
        ),
        children: [
          o && o.length > 0 && /* @__PURE__ */ f(
            se,
            {
              badgeProps: {
                variant: "dot",
                invisible: L.filter,
                color: "primary"
              },
              icon: `${C}/${F}/${_e}`,
              isToggled: c.filter,
              onToggle: () => z("filter")
            }
          ),
          r && r.length > 0 && /* @__PURE__ */ f(
            se,
            {
              badgeProps: {
                variant: "dot",
                invisible: L.sort,
                color: "primary"
              },
              icon: `${C}/${F}/${be}`,
              isToggled: c.sort,
              onToggle: () => z("sort")
            }
          )
        ]
      }
    ),
    [
      c,
      L,
      C,
      F,
      g,
      o,
      r
    ]
  ), he = m(
    () => /* @__PURE__ */ M(
      we,
      {
        direction: "row",
        ...H(
          N,
          V.stackRightActions,
          g
        ),
        children: [
          /* @__PURE__ */ f(
            le,
            {
              ownerState: {
                isDirty: A || I,
                automatic: u
              },
              icon: b,
              "aria-label": "refresh",
              onClick: k,
              variant: "outline"
            }
          ),
          Y
        ]
      }
    ),
    [g, A, I, u, b, k, Y]
  ), te = a(() => i.current ? i.current.getCurrentSorts() : [], [i]), re = a(
    (e) => {
      if (i.current) {
        const t = r?.find((K) => K.name === e.columnKey), h = t?.presence === "fixed";
        switch (e.action) {
          case "add": {
            const K = {
              id: i.current.getNewId(),
              field: {
                name: e.columnKey,
                type: t?.type || "string",
                urlIcon: t?.urlIcon || "",
                label: e.label
              },
              isSet: !0,
              fixed: h,
              fieldType: t?.type || "string",
              operator: e.direction
            };
            y((Fe) => ({ ...Fe, sort: !0 })), i.current.addExternalSort(K);
            break;
          }
          case "remove":
            h || i.current.removeExternalSort(
              e.columnKey
            );
            break;
        }
      }
    },
    [i, r]
  ), ne = a(
    (e) => {
      if (l.current)
        switch (e.action) {
          case "add":
            y((t) => ({ ...t, filter: !0 })), l.current.addExternalFilter(e.columnKey);
            break;
          case "openPopoverMenuFields":
            y((t) => ({ ...t, filter: !0 })), l.current.openPopoverMenuFields();
            break;
          default:
            return;
        }
    },
    [l]
  ), oe = a(() => l.current ? l.current.getCurrentFilters() : [], [l]), ie = m(
    () => /* @__PURE__ */ M(ye, { children: [
      /* @__PURE__ */ f(
        Ae,
        {
          ref: l,
          visibleRefresh: $,
          automatic: u,
          fields: o,
          initialAppliedFilters: v,
          onChangeFilters: X,
          withAllField: B,
          onDirty: Q
        }
      ),
      r ? /* @__PURE__ */ f(
        Ie,
        {
          ref: i,
          visibleRefresh: $,
          automatic: u,
          fields: r,
          initialAppliedSorts: D,
          onChangeSorts: ee,
          onDirty: Z
        }
      ) : null,
      q && /* @__PURE__ */ f(
        le,
        {
          ownerState: {
            automatic: u,
            isDirty: A || I
          },
          icon: b,
          "aria-label": "refresh",
          onClick: k
        }
      )
    ] }),
    [$, u, o, v, X, B, Q, r, D, ee, Z, q, A, I, b, k]
  ), Se = m(
    () => /* @__PURE__ */ f(
      xe,
      {
        direction: "row",
        ownerState: {
          showDynamicFilter: c.filter,
          showDynamicSort: c.sort
        },
        ...H(
          N,
          V.stackCustomHeader,
          g
        ),
        children: ie
      }
    ),
    [c, g, ie]
  ), pe = m(() => {
    if (!(!r || r.length === 0))
      return {
        sortsColumns: r.map((e) => e.name),
        sortsApplied: te().map((e) => ({
          columnKey: e.field.name,
          removable: !e.fixed,
          direction: e.operator
        })),
        onChange: re
      };
  }, [r, G.sorts, te, re]), Ce = m(() => {
    if (!(!o || o.length === 0))
      return {
        filterColumns: o.map((e) => ({
          name: e.name,
          multiple: e.multiple || !1,
          skipColumnValidation: e.skipColumnValidation || !1
        })),
        filtersApplied: oe().map((e) => ({
          columnKey: e.field.name,
          isValid: e.isSet
        })),
        onChange: ne
      };
  }, [o, G.filters, oe, ne]);
  return {
    leftActions: ge,
    rightActions: he,
    visibleCustomHeader: de,
    customHeaderComponent: Se,
    externalSortSettings: pe,
    externalFilterSettings: Ce
  };
};
export {
  Ge as useDynamicFilterAndSort
};
