import { jsxs as d, jsx as r } from "@emotion/react/jsx-runtime";
import { useState as z, useEffect as B } from "react";
import { useModuleDictionary as G, useEnvironment as L } from "@m4l/core";
import { useDrag as M, useDrop as K } from "react-dnd";
import { renderHeaderCell as T } from "react-data-grid";
import { NameColumnIconStyled as U, NameColumnStyled as V, IconColumnStyled as J, DraggableHeaderRootStyled as W, ButtonHeaderActionsStyled as q, DraggableWrapperInputBaseStyled as Q, IconSearchStyled as X, HeaderInputBaseStyled as Y } from "../../../../slots/DataGridSlot.js";
import { pathIcons as l } from "../../../../icons.js";
import { Icon as y } from "@m4l/base";
import { useFocusRef as Z } from "../../hooks/useFocusRef/useFocusRef.js";
import { useDataGrid as ee } from "../../../../hooks/shared/useDataGrid/useDataGrid.js";
import { useFilters as te } from "../../../../hooks/shared/useFilters/useFilters.js";
function fe(u) {
  const {
    onColumnsReorder: S,
    column: t,
    tabIndex: c,
    openPopover: x,
    ...C
  } = u, { ref: D, tabIndex: I } = Z(
    c !== void 0 && c >= 0
  ), { getLabel: b } = G(), {
    size: m,
    classes: w,
    reorderable: f,
    externalSortSettings: $,
    externalFilterSettings: k,
    currentRowHeightVariant: v
  } = ee(), { host_static_assets: a, environment_assets: i } = L(), { activeFilters: s, filters: R, onChangeFilter: p } = te(), [H, g] = z(R?.get(t.key) || ""), h = $?.sortsApplied?.find(
    (e) => e.columnKey === t.key
  ), F = k?.filtersApplied?.find(
    (e) => e.columnKey === t.key
  ), [{ isDragging: _ }, A] = M({
    type: "COLUMN_DRAG",
    item: { key: t.key },
    canDrag: () => f,
    collect: (e) => ({
      isDragging: e.isDragging()
    })
  }), [{ isOver: N }, O] = K({
    accept: "COLUMN_DRAG",
    canDrop: () => f,
    drop({ key: e }) {
      S(e, t.key);
    },
    /**
     * Recolecta el estado del monitor de drop para detectar si hay un elemento sobre esta columna
     */
    collect: (e) => ({
      isOver: e.isOver(),
      canDrop: e.canDrop()
    })
  }), P = (e) => {
    s && p && p(t, e.target.value), g(e.target.value);
  }, E = (e) => e === "asc" ? `${a}/${i}/${l.sortAsc}` : `${a}/${i}/${l.sortDesc}`, j = () => {
    const e = [];
    if (h) {
      const o = E(h.direction);
      e.push(
        /* @__PURE__ */ r(
          y,
          {
            src: o,
            size: "small",
            color: "text.secondary"
          },
          "sort-icon"
        )
      );
    }
    if (F?.isValid) {
      const o = `${a}/${i}/${l.filter2}`;
      e.push(
        /* @__PURE__ */ r(
          y,
          {
            src: o,
            size: "small",
            color: "text.secondary"
          },
          "filter-icon"
        )
      );
    }
    return e.length > 0 ? e : null;
  };
  B(() => {
    s || g("");
  }, [s]);
  const n = { ...t };
  if (n.withinHeaderRenderer && (n.name = n.withinHeaderRenderer(u)), !n.withinHeaderRenderer) {
    const e = j();
    if (e) {
      const o = () => {
        switch (t.align) {
          case "left":
            return "flex-start";
          case "center":
            return "center";
          case "right":
            return "flex-end";
          default:
            return "flex-start";
        }
      };
      n.name = /* @__PURE__ */ d(U, { ownerState: {}, style: { justifyContent: o() }, children: [
        /* @__PURE__ */ r(V, { ownerState: { size: m, currentRowHeightVariant: v }, children: n.name }),
        /* @__PURE__ */ r(J, { ownerState: {}, children: e })
      ] });
    }
  }
  return /* @__PURE__ */ d(
    W,
    {
      ownerState: {},
      className: w?.draggableHeaderRoot,
      ref: (e) => {
        A(e), O(e);
      },
      style: {
        opacity: _ ? 0.5 : 1,
        backgroundColor: N ? "#ececec" : void 0
      },
      onClick: (e) => {
        e.stopPropagation();
      },
      children: [
        /* @__PURE__ */ r(
          q,
          {
            ownerState: {},
            role: "button",
            "aria-label": `header-column-button-${t.key}`,
            onClick: (e) => {
              x?.(e.currentTarget, t.key);
            },
            children: /* @__PURE__ */ r(
              T,
              {
                column: n,
                tabIndex: c,
                ...C
              }
            )
          }
        ),
        s && (t?.withFilter === void 0 || t.withFilter === !0) && /* @__PURE__ */ d(Q, { ownerState: {}, children: [
          /* @__PURE__ */ r(
            X,
            {
              ownerState: {},
              src: `${a}/${i}/${l.search}`,
              color: "text.secondary",
              size: m
            }
          ),
          /* @__PURE__ */ r(
            Y,
            {
              ownerState: {},
              inputRef: D,
              placeholder: b("data_grid.filter_holder"),
              tabIndex: I,
              type: "text",
              onChange: P,
              value: H,
              inputProps: {
                "data-testid": `column-filter-input-${t.key}`,
                "aria-label": `column-filter-input-${t.key}`
              }
            }
          )
        ] })
      ]
    }
  );
}
export {
  fe as DraggableHeaderRenderer
};
