import { jsxs as h, jsx as d, Fragment as ne } from "@emotion/react/jsx-runtime";
import { forwardRef as oe, useRef as z, useState as _, useImperativeHandle as re, useMemo as M, useEffect as te } from "react";
import { useModuleDictionary as le, useEnvironment as ie } from "@m4l/core";
import se from "react-data-grid";
import { pathIcons as S } from "../../../../../../icons.js";
import { ColumnsConfigWrapperStyled as ae, ColumnsConfigDataGridStyled as de, ColumnsConfigSelColumnsStyled as ce, TableWrapperDataGridStyled as ue, ColumnsConfigActiosStyled as pe } from "../../../../../../slots/DataGridSlot.js";
import { DICTIONARY as s } from "../../../../../../dictionary.js";
import { ColumnInteractiveCheckFormatter as N } from "../../../../../../formatters/ColumnInteractiveCheckFormatter/formatter.js";
import { IconButton as I } from "../../../../../../../extended/mui/IconButton/IconButton.js";
function A(C, u) {
  return C.filter((r) => !r.hidden).map((r) => {
    const p = u.find((b) => b.key === r.key)?.groupable === !0, v = r.grouped === !0;
    return {
      key: r.key,
      name: u?.find((b) => b.key === r.key)?.name ?? "",
      visible: r.visible === void 0 ? !0 : r.visible,
      frozen: r.frozen === void 0 ? !1 : r.frozen,
      grouped: v,
      // Checkbox habilitado solo si groupable=true
      groupable: p,
      originalIndex: r.originalIndex,
      originalFrozen: r.originalFrozen,
      originalVisible: r.originalVisible,
      originalGrouped: r.originalGrouped ?? !1
    };
  });
}
const w = (C) => {
  const u = C !== void 0 ? `rdg-cell-align-${C}` : "";
  return {
    cellClass: u,
    headerCellClass: u
  };
}, me = oe(
  (C, u) => {
    const r = z(null), {
      onCloseSettings: E,
      columnsConfig: p,
      onChangeColumnsConfig: v,
      rowHeight: b,
      classes: F,
      size: G,
      columns: k,
      reorderable: U = !0
    } = C, { getLabel: i } = le(), [V, D] = _(!0), [o, c] = _(
      A(p, k)
    ), [y, P] = _(() => /* @__PURE__ */ new Set()), R = z(null), { host_static_assets: m, environment_assets: f } = ie();
    re(u, () => ({
      onClickIntro: q,
      current: R.current
    }));
    const B = M(() => {
      const e = [
        {
          key: "name",
          name: i(s.SETTINGS_COLUMN_NAME),
          width: 220,
          resizable: !0,
          type: "string",
          ...w("left")
        },
        {
          key: "originalIndex",
          name: i(s.SETTINGS_COLUMN_POSITION),
          width: 70,
          type: "number",
          ...w("center")
        },
        {
          key: "visible",
          name: i(s.SETTINGS_COLUMN_VISIBLE),
          width: 80,
          type: "boolean",
          renderCell: N,
          ...w("center")
        },
        {
          key: "frozen",
          name: i(s.SETTINGS_COLUMNS_FROZEN),
          width: 80,
          type: "boolean",
          renderCell: N,
          ...w("center")
        }
      ];
      return k.some(
        (n) => n.groupable === !0 || n.grouped === !0
      ) && e.push({
        key: "grouped",
        name: i(s.SETTINGS_COLUMN_GROUP),
        width: 80,
        type: "boolean",
        renderCell: N,
        // disabledKey hace que el checkbox esté deshabilitado cuando groupable=false
        disabledKey: "groupable",
        ...w("center")
      }), e;
    }, [i, k]), W = () => {
      c(o.map((e) => ({ ...e, visible: !0 })));
    }, K = () => {
      c(o.map((e) => ({ ...e, visible: !1 })));
    }, j = () => {
      c(
        o.map((e) => ({
          ...e,
          visible: e.originalVisible,
          frozen: e.originalFrozen,
          grouped: e.originalGrouped,
          index: e.originalIndex
        })).sort((e, t) => e.index - t.index)
      );
    };
    te(() => {
      V === !1 && c(
        A(p, k)
      ), D(!1);
    }, [p]);
    const l = M(() => {
      let e = -1;
      if (y.size !== 1)
        return e;
      const n = y.entries().next().value?.[1];
      return e = o.findIndex((a) => a.key === n), e;
    }, [o, y]), H = () => {
      if (l === -1)
        return -1;
      const e = [...o];
      e.splice(l, 1), e.splice(0, 0, o[l]), r.current?.selectCell({ idx: 0, rowIdx: 0 }), c(e);
    }, Y = () => {
      if (l === -1)
        return -1;
      const e = [...o];
      e.splice(l, 1), e.splice(e.length, 0, o[l]), r.current?.selectCell({ idx: 0, rowIdx: e.length - 1 }), c(e);
    }, $ = (e) => {
      if (l === -1)
        return -1;
      const t = [...o], n = t[l];
      t.splice(l, 1), t.splice(l + e, 0, n), r.current?.selectCell({
        idx: 0,
        rowIdx: l + e
      }), c(t);
    }, Z = (e) => {
      const t = o.findIndex((n) => n.key === e);
      if (t > -1)
        return {
          visible: o[t].visible,
          frozen: o[t].frozen
        };
    }, O = (e) => {
      const t = o.findIndex((n) => n.key === e.key);
      return t > -1 ? t : p.findIndex(
        (n) => n.key === e.key
      );
    }, q = () => {
      const e = o.filter((n) => n.grouped), t = p.map((n) => {
        const a = { ...n };
        if (!n.hidden) {
          const T = Z(n.key);
          T && (a.visible = T.visible, a.frozen = T.frozen);
          const x = o.findIndex(
            (g) => g.key === n.key
          );
          x > -1 && (a.index = x);
          const L = o.find((g) => g.key === n.key);
          if (L) {
            a.grouped = L.grouped;
            const g = e.findIndex(
              (ee) => ee.key === n.key
            );
            a.groupOrder = g > -1 ? g : x;
          }
        }
        return a;
      }).sort((n, a) => O(n) - O(a));
      v(t), E();
    }, J = () => {
    }, Q = (e) => {
      c(e);
    }, X = ({ row: e }) => {
      if (y.has(e.key))
        return;
      const t = /* @__PURE__ */ new Set([e.key]);
      P(t);
    };
    return /* @__PURE__ */ h(ae, { ownerState: {}, ref: R, children: [
      /* @__PURE__ */ h(de, { ownerState: {}, children: [
        /* @__PURE__ */ d(ce, { ownerState: { size: G }, children: i(s.SETTINGS_SEL_COLUMNS) }),
        /* @__PURE__ */ d(
          ue,
          {
            className: F?.tableWrapperDataGrid,
            ownerState: { size: G },
            children: /* @__PURE__ */ d(
              se,
              {
                ref: r,
                rowHeight: b,
                columns: B,
                rows: o,
                onRowsChange: Q,
                selectedRows: y,
                onSelectedRowsChange: J,
                onCellClick: X,
                rowKeyGetter: (e) => e.key,
                defaultColumnOptions: { resizable: !0, sortable: !0 }
              }
            )
          }
        )
      ] }),
      /* @__PURE__ */ h(pe, { ownerState: {}, children: [
        U && /* @__PURE__ */ h(ne, { children: [
          /* @__PURE__ */ d(
            I,
            {
              tooltip: i(s.SETTINGS_MOVE_FIRST),
              onClick: H,
              "aria-label": "move first place",
              disabled: l < 1,
              icon: `${m}/${f}/${S.moveFirstPlace}`
            }
          ),
          /* @__PURE__ */ d(
            I,
            {
              tooltip: i(s.SETTINGS_MOVE_UP),
              onClick: () => $(-1),
              "aria-label": "move up place",
              disabled: l < 1,
              icon: `${m}/${f}/${S.moveUpPlace}`
            }
          ),
          /* @__PURE__ */ d(
            I,
            {
              tooltip: i(s.SETTINGS_MOVE_LAST),
              onClick: Y,
              "aria-label": "move last place",
              disabled: l === o.length - 1 || l === -1,
              icon: `${m}/${f}/${S.moveLastPlace}`
            }
          ),
          /* @__PURE__ */ d(
            I,
            {
              tooltip: i(s.SETTINGS_MOVE_DOWN),
              onClick: () => $(1),
              "aria-label": "move down place",
              disabled: l === o.length - 1 || l === -1,
              icon: `${m}/${f}/${S.moveDownPlace}`
            }
          )
        ] }),
        /* @__PURE__ */ d(
          I,
          {
            tooltip: i(s.SETTINGS_VISIBLE_ALL),
            onClick: W,
            "aria-label": "check visible all",
            icon: `${m}/${f}/${S.checkAll}`
          }
        ),
        /* @__PURE__ */ d(
          I,
          {
            tooltip: i(s.SETTINGS_NO_VISIBLE_ALL),
            onClick: K,
            "aria-label": "un check all",
            icon: `${m}/${f}/${S.uncheckAll}`
          }
        ),
        /* @__PURE__ */ d(
          I,
          {
            tooltip: i(s.SETTINGS_RESTORE),
            onClick: j,
            "aria-label": "Restore columns",
            icon: `${m}/${f}/${S.restoreColumns}`
          }
        )
      ] })
    ] });
  }
);
me.displayName = "ColumnsConfig";
export {
  me as ColumnsConfig,
  w as getAlignClass
};
