import { createStore as T } from "zustand";
import { devtools as x } from "zustand/middleware";
import { immer as N } from "zustand/middleware/immer";
import { getCookiesContainer as L, getDataFromResponse as b, getParmsFromValue as R, setColapsedLayoutBreakPoints as S, COOKIE_BREAKPOINT_LAYOUTS as $, DEBOUCED_SAVE_TIME as z, DEFAULT_WINDOW as O, MARGIN_GRIDLAYOUT as m, COOKIE_WINDOWS as B, deleteLayoutFromBreakPoints as H, RESPONSIVE_ROW_HEIGHTS as U, PADDING_GRIDLAYOUT as E, NORMALIZED_COLS as G, addArea as _, DEFAULT_AREA as K, getSelectedAreaIdFromCookies as Q, COOKIE_WINDOW_SELECTED as V, COOKIE_AREAS_ADMIN_CONTAINER_ID as M, COOKIE_AREAS_ADMIN_ID as F } from "./helpers/helper.js";
import { createDynamicMFStore as w } from "../../../WindowBase/contexts/DynamicMFParmsContext/store.js";
import Y from "lodash-es/cloneDeep";
import j from "lodash-es/debounce";
import { generateModuleCount as P } from "./helpers/generateModuleCount.js";
import { AREAS_STORE_ID as q } from "../../constants.js";
import { helperSelectLayout as C } from "./helpers/selectLayout.js";
import { deleteCookie as I, setCookie as p, getCookie as v } from "../../../../helpers/cookies/cookies.js";
import { isEqualLayouts as Z } from "../../../GridLayout/utils.js";
import { cloneLayouts as J, addLayoutItemToBreakPoints as X } from "../../../GridLayout/subcomponents/Responsive/responsiveUtils.js";
const g = (f, k) => {
  const { enabled: W = !1 } = k;
  return W && process.env.NODE_ENV === "development" ? x(f, k) : f;
}, po = (f, k = !1) => {
  const W = {
    currentAreaId: "",
    currentModuleId: "",
    areasIds: [],
    hashAreas: {},
    hashWindows: {},
    windowsModalsIds: [],
    ...f
  };
  return T(
    g(
      N((i, a) => ({
        ...W,
        areasActions: {
          /**
           * Inicializa el store de areas
           */
          init: () => {
            if (a().ownerState?.status !== "init")
              return;
            if (!a().loadAreasFromNetwork) {
              a().areasActions.addArea(), i((r) => {
                r.ownerState.status = "loaded";
              });
              return;
            }
            i((r) => {
              r.ownerState.status = "loading";
            });
            const o = v({
              networkOperation: a().networkOperation,
              params: {
                f: [
                  { n: "container_id", o: "e", o1: M },
                  { n: "id", o: "e", o1: F }
                ]
              }
            }), e = a().networkOperation({
              method: "GET",
              endPoint: "areas",
              parms: {},
              toastSuccess: !1
            });
            let s;
            Promise.allSettled([e, o]).then(([r, n]) => {
              if (r?.status === "fulfilled") {
                const t = r?.value?.data;
                i((d) => {
                  if (t && Array.isArray(t) && t.length > 0)
                    for (let l = 0; l < t.length; l++) {
                      const h = {
                        ...K,
                        ...t[l],
                        loadWindows: !0
                        //Se indica que si se carguen las ventas debido a que viene de la API
                      };
                      d.hashAreas[h.id] = h, d.areasIds.push(h.id);
                    }
                  else
                    _(d);
                });
              }
              n.status === "fulfilled" && (s = Q(n?.value));
            }).finally(() => {
              if (i((r) => {
                r.ownerState.status = "loaded";
              }), a().areasIds.length > 0 && a().currentAreaId === "") {
                const r = s && a().areasIds?.includes?.(s) ? s : a().areasIds[0];
                a().areasActions.selectArea(r);
              }
            });
          },
          /**
           * Acción encargada de añadir un área de trabajo en blanco
           */
          addArea: () => {
            let o = "";
            return i((e) => {
              o = _(e);
            }), a().areasActions.selectArea(o), o;
          },
          /**
           * editArea store
           */
          editArea: (o, e) => {
            i((s) => {
              s.hashAreas[o] && (s.hashAreas[o].name = e, s.loadAreasFromNetwork && s.networkOperation({
                method: "PATCH",
                endPoint: `areas/${o}`,
                data: { name: e },
                toastSuccess: !1,
                toastError: !1
              }));
            });
          },
          /**
           * deleteArea store
           */
          deleteArea: (o) => {
            let e = "";
            i((s) => {
              if (!s.hashAreas[o] || s.areasIds.length < 2)
                return;
              const n = s.areasIds.indexOf(o);
              if (n > -1) {
                for (const d in s.hashWindows)
                  s.hashWindows[d].areaId === o && delete s.hashWindows[d];
                const t = s.areasIds.findIndex((d) => d === o);
                s.areasIds.splice(n, 1), delete s.hashAreas[o], s.currentAreaId === o && (e = s.areasIds[t <= s.areasIds.length - 1 ? t : s.areasIds.length - 1]);
              }
              s.loadAreasFromNetwork && s.networkOperation({
                method: "DELETE",
                endPoint: `areas/${o}`,
                parms: {},
                toastSuccess: !1,
                toastError: !1
              }), s.loadCookiesFromNetwork && I({
                networkOperation: a().networkOperation,
                data: { f: [{ n: "container_id", o: "c", o1: o }] }
              }).catch(() => {
              });
            }), e && a().areasActions.selectArea(e);
          },
          /**
           * selectArea store
           */
          selectArea: (o) => {
            i((e) => {
              e.currentAreaId = o, e.hashAreas[o].currentLayoutId ? e.currentModuleId = e.hashWindows[e.hashAreas[o].currentLayoutId].moduleId : e.currentModuleId = "";
            }), a().hashAreas[o].status === "init" && (a().hashAreas[o].loadWindows ? a().areaActions.loadWindowsFromApi(o) : i((e) => {
              e.hashAreas[o].status = "loaded";
            })), a().loadCookiesFromNetwork && p({
              networkOperation: a().networkOperation,
              endPoint: `${M}/${F}`,
              value: { selectedAreaId: o }
            }).catch(() => {
            });
          },
          /**
           * setHandlerGetLabel
           */
          setHandlerGetLabel: (o) => {
            i((e) => {
              e.getLabel = o;
            });
          },
          /**
           * setExternalState
           */
          setExternalState: (o) => {
            i((e) => {
              e.ownerState = { ...e.ownerState, ...o };
            });
          }
        },
        areaActions: {
          /**
           * addWindow store
           */
          addWindow: (o) => {
            const e = `${a().currentAreaId}_window_${(/* @__PURE__ */ new Date()).getTime()}_${(Math.random() * 1e3).toFixed(0)}`;
            o.emergeType === "layout" ? a().areaActions.addLayout(
              a().currentAreaId,
              e,
              o
            ) : o.emergeType === "popup" ? a().areaActions.addPopup(
              a().currentAreaId,
              e,
              o
            ) : o.emergeType === "modal" && a().areaActions.addWindowModal(
              a().currentAreaId,
              e,
              o
            );
          },
          /**
           * addLayout store
           */
          addLayout: (o, e, s) => {
            let r = e;
            const n = !1, t = P(
              a().currentAreaId,
              s.moduleId,
              a().hashWindows
            ), d = {
              ...s.layoutProps,
              i: e,
              isDraggable: !0,
              isResizable: !0,
              freeMove: n
            };
            i((l) => {
              const h = l.hashAreas[o];
              if (h) {
                if (s.replaceMeId)
                  for (let c = 0; c < h.layoutItemsIds.length; c++) {
                    const u = h.layoutItemsIds[c], A = l.hashWindows[u];
                    if (A.replaceMeId === s.replaceMeId) {
                      r = u, A.dynamicMFStore.getState().actions.changeData(s.dynamicParams);
                      break;
                    }
                  }
                if (r === e) {
                  const c = w({
                    dynamicMFParameters: s.dynamicParams
                  });
                  l.hashWindows[e] = {
                    ...s,
                    areaId: o,
                    windowId: e,
                    onClose: (u) => {
                      a().areaActions.closeLayout(o, u);
                    },
                    ...O,
                    dynamicMFStore: c,
                    moduleCount: t
                  }, h.layoutItemsIds.push(e), h.maximizedId && (h.maximizedId = e), h.layouts = X(
                    h.layouts,
                    d,
                    G,
                    [m, m],
                    [E, E],
                    U,
                    h.containerHeight,
                    h.currentBreakpoint
                  ), h.currentBreakpoint === "xxs" && (h.maximizedId = e), C(l, o, e, !0), a().popupsProviderMethods.setSelectedPopupId(o, void 0);
                }
              }
            }), a().areaActions.saveLayouts(o), a().areaActions.bouncedSaveBreakpointsLayouts(o);
          },
          /**
           * closeLayout
           */
          closeLayout: (o, e) => {
            i((s) => {
              const r = s.hashAreas[o];
              if (!r)
                return;
              const n = r.layoutItemsIds.indexOf(e);
              n > -1 && r.layoutItemsIds.splice(n, 1), H(r, e), delete s.hashWindows[e], s.hashAreas[o].currentLayoutId === e && C(s, o, "");
            }), a().areaActions.saveLayouts(o), a().hashAreas[o].maximizedId === e && a().areaActions.maximizeLayout(o);
            for (let s = 0; s < a().hashAreas[o].layoutItemsIds.length; s++) {
              const r = a().hashAreas[o].layoutItemsIds[s], n = a().hashWindows[r];
              n && n.parentId === e && a().areaActions.closeLayout(o, n.windowId);
            }
            a().popupsProviderMethods.closeAllPopupsByParentId(e);
          },
          /**
           * saveLayouts
           */
          saveLayouts: (o) => {
            if (!a().loadCookiesFromNetwork)
              return;
            let e = 0;
            const s = a().hashAreas[o];
            if (!s)
              return;
            const r = {};
            for (let n = 0; n < s.layoutItemsIds.length; n++) {
              const t = s.layoutItemsIds[n];
              if (a().hashWindows[t] && a().hashWindows[t].winType === "microfrontend") {
                const d = a().hashWindows[t], l = {
                  winType: !0,
                  emergeType: !0,
                  title: !0,
                  url_icon: !0,
                  windowOptions: !0,
                  moduleId: !0,
                  windowId: !0,
                  mfProps: !0,
                  moduleCount: !0,
                  iconUrl: !0
                }, h = {};
                for (const c in l)
                  h[c] = d[c];
                r[t] = h, e++;
              }
            }
            e > 0 ? p({
              networkOperation: a().networkOperation,
              endPoint: `${s.id}/${B}`,
              value: r
            }).catch(() => {
            }) : I({
              networkOperation: a().networkOperation,
              data: { f: [{ n: "container_id", o: "c", o1: s.id }] }
            }).catch(() => {
            });
          },
          /**
           * addPopup store
           */
          addPopup: (o, e, s) => {
            let r = e;
            i((n) => {
              if (n.hashAreas[o]) {
                if (s.replaceMeId) {
                  for (const d in n.hashWindows)
                    if (n.hashWindows[d].replaceMeId === s.replaceMeId) {
                      const l = n.hashWindows[d];
                      r = d, l.dynamicMFStore.getState().actions.changeData(s.dynamicParams), a().popupsProviderMethods.bringPopupOnFront(d, !0);
                      break;
                    }
                }
                if (r === e) {
                  const d = w({
                    dynamicMFParameters: s.dynamicParams
                  });
                  n.hashWindows[e] = {
                    ...s,
                    ...O,
                    areaId: o,
                    windowId: e,
                    onClose: (y) => {
                      a().areaActions.closeLayout(o, y);
                    },
                    dynamicMFStore: d
                  };
                  const { emergeType: l, popupProps: h, ...c } = s, u = (y, eo, D) => {
                    A ? D === "select" && a().areaActions.selectLayout(y, A) : a().areaActions.selectLayout(y, "");
                  }, A = s.parentId;
                  a().popupsProviderMethods.addPopup({
                    ...c,
                    ...h,
                    popupId: e,
                    groupId: o,
                    dynamicMFStore: d,
                    dynamicParams: s.dynamicParams,
                    onRemove: () => a().areaActions.closePopup(o, e),
                    /**
                     *
                     */
                    onSelectedPopupIdChange: u,
                    allowHeightResizeContainer: !0,
                    allowWidthResizeContainer: !1,
                    bounds: {
                      left: m,
                      top: m,
                      right: -m,
                      bottom: -m
                    }
                  });
                }
              }
            });
          },
          /**
           * closePopup
           */
          closePopup: (o, e) => {
            i((s) => {
              s.hashAreas[o] && delete s.hashWindows[e];
            });
          },
          /**
           * closeWindowModal
           */
          closeWindowModal: (o) => {
            i((e) => {
              const s = e.windowsModalsIds.findIndex((r) => r === o);
              s > -1 && e.windowsModalsIds.splice(s, 1), delete e.hashWindows[o];
            });
          },
          /**
           * addWindowModal
           */
          addWindowModal: (o, e, s) => {
            i((r) => {
              const n = w({
                dynamicMFParameters: s.dynamicParams
              });
              r.windowsModalsIds.push(e);
              const t = P(
                a().currentAreaId,
                s.moduleId,
                a().hashWindows
              );
              r.hashWindows[e] = {
                ...s,
                areaId: o,
                windowId: e,
                ...O,
                onClose: a().areaActions.closeWindowModal,
                dynamicMFStore: n,
                moduleCount: t
              };
            });
          },
          bouncedSaveBreakpointsLayouts: j(
            (o) => {
              if (!a().loadCookiesFromNetwork)
                return;
              const e = {
                ...a().hashAreas[o].layouts
              }, s = {};
              for (const r in e) {
                const n = e[r];
                e[r] = n.filter((t) => t.i === "none" ? !1 : a().hashAreas[o].layoutItemsIds.indexOf(t.i) > -1), e[r].length > 0 && (s[r] = e[r]);
              }
              Object.keys(s).length > 0 && p({
                networkOperation: a().networkOperation,
                endPoint: `${a().hashAreas[o].id}/${$}`,
                value: s
              }).catch(() => {
              });
            },
            z,
            {
              leading: !0,
              trailing: !0
            }
          ),
          /**
           * onBreakpointsLayoutsChange
           */
          onBreakpointsLayoutsChange: (o, e, s) => {
            Z(a().hashAreas[o].layouts, s) || (i((r) => {
              r.hashAreas[o].layouts = J(s);
            }), a().hashAreas[o].maximizedId || a().areaActions.bouncedSaveBreakpointsLayouts(o));
          },
          /**
           * containerChange
           */
          onContainerChange: (o, e) => {
            i((s) => {
              s.hashAreas[o].containerHeight = e.containerHeight, s.hashAreas[o].currentBreakpoint = e.breakpoint;
            });
          },
          /**
           * selectLayout
           */
          selectLayout: (o, e) => {
            a().hashAreas[o].currentLayoutId !== e && i((s) => {
              C(s, o, e);
            });
          },
          /**
           * unColapseLayoutItem
           */
          unColapseLayoutItem: (o, e) => {
            i((s) => {
              S(s.hashAreas[o], e, !1);
            });
          },
          /**
           * colapseLayoutItem
           */
          colapseLayoutItem: (o, e) => {
            !a().hashAreas[o].maximizedId && a().hashWindows[e] && i((s) => {
              S(s.hashAreas[o], e, !0);
            });
          },
          /**
           * minimizeLayout
           */
          maximizeLayout: (o, e) => {
            i((s) => {
              const r = s.hashAreas[o];
              r && (r.maximizedId = e);
            }), e && a().areaActions.selectLayout(o, e);
          },
          /**
           * normalizeLayouts
           */
          normalizeLayouts: (o) => {
            i((e) => {
              const s = e.hashAreas[o];
              s && (s.maximizedId = void 0);
            });
          },
          /**
           * loadWindowsFromApi
           */
          loadWindowsFromApi: (o) => {
            const e = a().hashAreas[o];
            if (e && e.status === "init") {
              if (!a().loadAreasFromNetwork || !a().loadCookiesFromNetwork || !e.loadWindows) {
                i((s) => {
                  s.hashAreas[o].status = "loaded";
                });
                return;
              }
              i((s) => {
                s.hashAreas[o].status = "loading";
              }), v({
                networkOperation: a().networkOperation,
                params: { f: [{ n: "container_id", o: "e", o1: o }] }
              }).then((s) => {
                if (!a().hashAreas[o])
                  return;
                const n = s.data;
                i((t) => {
                  const d = t.hashAreas[o], { newBreakPointsLayouts: l, newHashLayoutItems: h } = b(
                    n,
                    t,
                    o
                  );
                  d.layouts = l, d.layoutItemsIds = h, d.status = "loaded";
                  const c = R(V, n) || { currentLayoutId: "" };
                  C(t, o, c?.currentLayoutId || "", !1);
                });
              }).catch((s) => {
                i((r) => {
                  r.hashAreas[o].status = "loaded";
                });
              });
            }
          }
          // /**
          //  * setIsDraggingResizingPopup
          //  */
          // setIsDraggingResizingPopup: (areaId: string, newIsDraggingResizingPopup: boolean) => {
          //   set(state => {
          //     state.hashAreas[areaId].isDraggingResizingPopup = newIsDraggingResizingPopup;
          //   });
          // },
        },
        windowActions: {
          /**
           * setActions
           */
          setActions: (o, e, s, r) => {
            i((n) => {
              n.hashWindows[o] && (n.hashWindows[o].moduleActions = Y(e), n.hashWindows[o].version = s, n.hashWindows[o].buildTime = r);
            });
          },
          /**
           * getCookie
           */
          getCookie: (o, e) => a().hashWindows[o] ? a().hashWindows[o].cookies.windowCookies[e] || a().hashWindows[o].cookies.moduleCookies[e] : {},
          /**
           * getCookies
           */
          getCookies: (o, e) => a().hashWindows[o] ? e === "window" ? a().hashWindows[o].cookies.windowCookies : a().hashWindows[o].cookies.moduleCookies : {},
          /**
           * setCookie
           */
          setCookie: (o, e, s, r) => {
            i((n) => {
              const t = n.hashWindows[o];
              t && (a().loadCookiesFromNetwork && p({
                networkOperation: a().networkOperation,
                endPoint: `${s === "module" ? t.moduleId : o}/${e}`,
                value: r
              }).catch(() => {
              }), s === "window" ? t.cookies.windowCookies[e] = r : t.cookies.moduleCookies[e] = r);
            });
          },
          /**
           * close window
           */
          close: (o, e = !0) => {
            const s = a().hashWindows[o];
            if (s) {
              if (s.fnQueryClose && e) {
                s.fnQueryClose();
                return;
              }
              const r = s.onClose;
              r && r(s.windowId);
            }
          },
          /**
           * startProgress
           */
          startProgress: (o) => {
            i((e) => {
              e.hashWindows[o] && (e.hashWindows[o].loading = !0);
            });
          },
          /**
           * stopProgress
           */
          stopProgress: (o) => {
            i((e) => {
              e.hashWindows[o] && (e.hashWindows[o].loading = !1);
            });
          },
          /**
           * loadCookiesFromApi
           */
          loadCookiesFromApi: (o) => {
            const e = a().hashWindows[o];
            if (e && e.status === "init") {
              if (!a().loadCookiesFromNetwork) {
                i((s) => {
                  s.hashWindows[o].status = "loaded";
                });
                return;
              }
              i((s) => {
                s.hashWindows[o].status = "loading";
              }), v({
                networkOperation: a().networkOperation,
                params: {
                  f: [
                    { n: "container_id", o: "e", o1: e.windowId },
                    { n: "container_id", o: "e", o1: e.moduleId }
                  ]
                }
              }).then((s) => {
                i((r) => {
                  const n = r.hashWindows[o];
                  n && (n.cookies.moduleCookies = L(
                    s.data,
                    n.moduleId
                  ), n.cookies.windowCookies = L(s.data, o), n.status = "loaded");
                });
              }).catch((s) => {
                i((r) => {
                  r.hashWindows[o] && (r.hashWindows[o].status = "loaded");
                });
              });
            }
          },
          /**
           * saveModuleCookies
           */
          saveModuleCookies: (o) => {
            const e = a().hashWindows[o];
            if (e) {
              if (!a().loadCookiesFromNetwork)
                return;
              for (const s in e.cookies.windowCookies) {
                const r = e.cookies.windowCookies[s];
                p({
                  networkOperation: a().networkOperation,
                  endPoint: `${e.moduleId}/${s}`,
                  value: r
                }).catch(() => {
                });
              }
            }
          },
          /**
           * setModuleCookies
           */
          resetModuleCookies: (o) => {
            const e = a().hashWindows[o];
            if (e) {
              if (!a().loadCookiesFromNetwork)
                return;
              I({
                networkOperation: a().networkOperation,
                data: {
                  f: [
                    {
                      n: "id",
                      o: "c",
                      o1: e.moduleId
                    }
                  ]
                }
              }).catch(() => {
              });
            }
          },
          /**
           * setFnQueryClose
           */
          setFnQueryClose: (o, e) => {
            i((s) => {
              s.hashWindows[o].fnQueryClose = e;
            });
          },
          /**
           * setWindowTitle
           */
          setWindowTitle: (o, e) => {
            i((s) => {
              s.hashWindows[o].title = e;
            });
          },
          /**
           * setWindowSubtitle
           */
          setWindowSubTitle: (o, e) => {
            i((s) => {
              s.hashWindows[o].subTitle = e;
            });
          },
          /**
           * setWindowEditionInfo
           */
          setWindowEditionInfo: (o, e) => {
            i((s) => {
              s.hashWindows[o].editionInfo = e;
            });
          }
        }
      })),
      { name: `${q}: ${f.storeId}`, enabled: k }
    )
  );
};
export {
  po as createAreasStore
};
