import { jsx as m, jsxs as oe } from "@emotion/react/jsx-runtime";
import { useMemo as C, useState as W, useRef as q, useEffect as x } from "react";
import re, { TreeDataGrid as te } from "react-data-grid";
import { DndProvider as ne } from "react-dnd";
import { HTML5Backend as le } from "react-dnd-html5-backend";
import { TableContainerStyled as se, TableWrapperDataGridStyled as ie } from "../../slots/DataGridSlot.js";
import { useSortColumnsRows as ce } from "./hooks/useSortColumnsRows/useSortColumnsRows.js";
import { getGroupBy as ae } from "./helpers/getGroupBy/getGroupBy.js";
import { defaultRowGrouper as ue } from "./helpers/defaultRowGrouper/defaultRowGrouper.js";
import { createRowCellsBackgroundMap as me, processColumnsWithRowCellsBackground as de } from "./helpers/rowCellsBackground/rowCellsBackground.js";
import { useHeaderMenuActions as fe } from "./hooks/useHeaderMenuActions/useHeaderMenuActions.js";
import { filterHeight as z } from "./subcomponents/SelectColumn/SelectColumn.js";
import { HeaderRenderClick as pe } from "./subcomponents/HeaderRenderClick/HeaderRenderClick.js";
import { getDefaultAction as he } from "../../helpers/shared/getDefaultAction/getDefaultAction.js";
import { useFilters as Ce } from "../../hooks/shared/useFilters/useFilters.js";
import { useDataGrid as we } from "../../hooks/shared/useDataGrid/useDataGrid.js";
import { CheckboxFormatter as ge } from "./subcomponents/CheckboxFormatter/CheckboxFormatter.js";
function Oe(L) {
  const {
    columns: $,
    rows: j,
    onRowsChange: R,
    rowKeyGetter: r,
    selectedRows: n,
    onSelectedRowsChange: t,
    defaultColumnOptions: N,
    focusOnRowKey: l,
    smoothScroll: v = !0,
    rowCellsBackground: d,
    treeProps: s,
    ...b
  } = L, k = (e) => /* @__PURE__ */ m(
    ge,
    {
      ...e,
      tabIndex: e.tabIndex
    }
  ), { finalColumns: i, finalRows: c } = ce(
    $,
    j,
    C(
      () => ({
        /**
         * Función que abre el menú de acciones para una columna
         */
        openPopover: (e, o) => {
          e instanceof HTMLDivElement && E({
            anchorEl: e,
            columnKey: o
          });
        }
      }),
      []
    )
  ), { activeFilters: G } = Ce(), {
    onChangeColumnWidth: V,
    setRowsCount: _,
    currentRowHeight: w,
    currentRowHeaderHeight: p,
    currentRowHeightVariant: g,
    size: J,
    sortColumns: f,
    setSortColumns: H,
    columnsConfig: I,
    rowActionsGetter: B
  } = we(), Q = C(() => s ? ae(I) : [], [I, s]), U = s?.rowGrouper ?? ue, A = C(() => {
    if (d)
      return typeof d == "function" ? d : me(d);
  }, [d]), D = C(
    () => de(
      i,
      A,
      r,
      g
    ),
    [i, A, r, g]
  ), a = q(null), [h, E] = W({
    anchorEl: null,
    columnKey: null
  }), S = q(void 0), [X, K] = W(!1), T = (e) => {
    X && (H(e), K(!1));
  }, Y = (e) => {
    K(!0), H(e);
  }, M = ({ row: e }) => {
    if (n && t) {
      if (n.entries().next().value && n.entries().next().value?.[1] === r(e))
        return;
      const o = /* @__PURE__ */ new Set([r(e)]);
      t(o);
    }
  }, O = ({ row: e }) => {
    if (n && t && e) {
      const o = r(e);
      n.has(o) || t(/* @__PURE__ */ new Set([o]));
    }
  }, P = ({ row: e }) => {
    if (!B)
      return;
    const o = B(e), u = he(o);
    u?.onClick && u.onClick(e);
  };
  x(() => {
    let e = 0;
    for (const o of i) {
      const u = f.findIndex(
        (ee) => o.key === ee.columnKey
      );
      u !== -1 ? a.current?.element?.querySelector(
        `[role="columnheader"][aria-colindex="${e + 1}"]`
      )?.setAttribute("aria-columnsort", `${f[u].direction}`) : a.current?.element?.querySelector(
        `[role="columnheader"][aria-colindex="${e + 1}"]`
      )?.removeAttribute("aria-columnsort"), e++;
    }
  }, [f, i]), x(() => {
    _(c.length);
  }, [c]), x(() => {
    if (!l) {
      S.current = void 0;
      return;
    }
    if (S.current === l)
      return;
    const e = c.findIndex(
      (o) => r(o) === l
    );
    if (e !== -1) {
      const o = a.current?.element;
      o?.style && (o.style.scrollBehavior = v ? "smooth" : "auto"), a.current?.scrollToCell({ rowIdx: e }), o?.style && requestAnimationFrame(() => {
        o.style.scrollBehavior = "";
      }), t && t(/* @__PURE__ */ new Set([l])), S.current = l;
    }
  }, [l, c, r, t, v]);
  const F = (e, o) => {
    V(i[e].key, o);
  }, y = {
    resizable: !0,
    sortable: !0,
    ...N || {}
  }, Z = fe(
    h.columnKey,
    i,
    !!y.sortable,
    Y
  );
  return /* @__PURE__ */ m(se, { ownerState: {}, id: "WrapperTable", children: /* @__PURE__ */ oe(
    ie,
    {
      ownerState: { size: J, currentRowHeightVariant: g, currentRowHeight: w },
      children: [
        /* @__PURE__ */ m(ne, { backend: le, context: window, children: s ? /* @__PURE__ */ m(
          te,
          {
            className: "rdg-light",
            ref: a,
            headerRowHeight: G ? p + z : p,
            columns: D,
            sortColumns: f,
            onSortColumnsChange: T,
            onColumnResize: F,
            rows: c,
            onRowsChange: R,
            selectedRows: n,
            onSelectedRowsChange: t,
            onCellClick: M,
            onCellDoubleClick: P,
            onSelectedCellChange: O,
            rowHeight: w,
            rowKeyGetter: r,
            renderers: {
              renderCheckbox: k
            },
            defaultColumnOptions: y,
            groupBy: Q,
            rowGrouper: U,
            expandedGroupIds: s.expandedGroupIds,
            onExpandedGroupIdsChange: s.onExpandedGroupIdsChange,
            ...b
          }
        ) : /* @__PURE__ */ m(
          re,
          {
            className: "rdg-light",
            ref: a,
            headerRowHeight: G ? p + z : p,
            columns: D,
            sortColumns: f,
            onSortColumnsChange: T,
            onColumnResize: F,
            rows: c,
            onRowsChange: R,
            selectedRows: n,
            onSelectedRowsChange: t,
            onCellClick: M,
            onCellDoubleClick: P,
            onSelectedCellChange: O,
            rowHeight: w,
            rowKeyGetter: r,
            renderers: {
              renderCheckbox: k
            },
            defaultColumnOptions: y,
            ...b
          }
        ) }),
        h.columnKey && h.anchorEl instanceof HTMLDivElement && /* @__PURE__ */ m(
          pe,
          {
            externalOpen: h.anchorEl,
            onOpen: (e) => {
              e || E({
                anchorEl: null,
                columnKey: null
              });
            },
            menuActions: Z
          }
        )
      ]
    }
  ) });
}
export {
  Oe as TableView
};
