import { jsx as l, jsxs as oe } from "@emotion/react/jsx-runtime";
import { useEnvironment as se, useModuleSkeleton as ce, useModuleDictionary as ae } from "@m4l/core";
import { useTheme as ie } from "@mui/material";
import { useForkRef as le } from "@mui/material/utils";
import ue from "clsx";
import fe, { forwardRef as me, useMemo as h, useState as de, useRef as k, useCallback as S, useEffect as V } from "react";
import { useComponentSize as Se } from "../../../../hooks/useComponentSize/index.js";
import { ArrowDownStyled as Ae, AdormentStyled as he, SelectRootStyled as we, SkeletonSelectStyled as ye, MenuItemListStyled as Ce, MenuItemNoOptionStyled as ge, LabelPlaceholerStyled as Ee, RenderValueContainerStyled as _, RenderValueTypography as Re } from "./slots/SelectSlots.js";
import { ICON_ARROW_DOWN as Ie, SELECT_CLASSES as m, SELECT_KEY_COMPONENT as Me } from "./constants.js";
import { SELECT_DICTIONARY as pe } from "./dictionary.js";
import { getPropDataTestId as ve } from "../../../../test/getNameDataTestId.js";
import { selectStyles as O } from "./Select.styles.js";
import { Chip as Ne } from "../../../Chip/Chip.js";
import { SelectSlots as xe } from "./slots/SelectEnum.js";
const Le = '[aria-label="Paper-popover-root"]';
function De(p) {
  const w = p?.closest(Le);
  return w instanceof HTMLElement ? w : null;
}
const qe = me(
  function({
    value: w = null,
    options: u = [],
    multiple: s,
    onChange: A,
    size: W = "medium",
    disabled: r = !1,
    error: C = !1,
    variant: g = "outlined",
    placeholder: j,
    className: B,
    dataTestId: K,
    readOnly: n = !1,
    MenuProps: c,
    ...v
  }, $) {
    const { currentSize: E } = Se(W), { host_static_assets: F, environment_assets: H } = se(), Y = ce(), { getLabel: q } = ae(), i = E === "small" || E === "medium" ? E : "medium", N = `${F}/${H}/${Ie}`, o = h(() => w, [w]), [f, y] = de(!1), R = k(null), x = k(null), L = ie(), d = h(() => ({
      size: i,
      disabled: r,
      error: C,
      variant: g,
      multiple: s,
      readOnly: n
    }), [i, r, C, g, s, n]), D = De(R.current), T = f ? (R.current?.offsetWidth ?? 0) + 1 : void 0, z = h(() => {
      const e = typeof O?.menuPaper == "function" ? O.menuPaper({ theme: L, menuPaperMinWidth: T }) : {};
      return Array.isArray(c?.sx) ? [e, ...c.sx] : c?.sx ? [e, c.sx] : e;
    }, [T, c?.sx, L]), b = h(() => ({
      ...c,
      anchorOrigin: c?.anchorOrigin ?? {
        vertical: "bottom",
        horizontal: "left"
      },
      container: c?.container ?? D ?? void 0,
      disableScrollLock: c?.disableScrollLock ?? !0,
      sx: z,
      transformOrigin: c?.transformOrigin ?? {
        vertical: "top",
        horizontal: "left"
      }
    }), [D, c, z]), G = S((e) => {
      if (n || r)
        return;
      const t = e.target.value;
      if (A)
        if (s) {
          if (Array.isArray(t)) {
            const a = u.filter((M) => t.includes(M.id));
            A(a);
          }
        } else {
          const a = u.find((M) => M.id === t);
          a && A(a);
        }
    }, [s, A, u, n, r]), J = S((e) => {
      if (!(n || r) && s && Array.isArray(o)) {
        const t = u.filter((a) => a.id !== e.id && o.includes(a.id));
        A?.(t);
      }
    }, [s, o, A, u, n, r]), I = S(() => {
      if (!(r || n)) {
        if (s) {
          f || y(!0);
          return;
        }
        y(!f);
      }
    }, [r, n, s, f]), P = h(() => () => /* @__PURE__ */ l(
      Ae,
      {
        ownerState: { ...d },
        icon: N,
        disabled: r || n,
        size: i,
        onClick: I,
        rotationAngle: f ? 180 : 0
      }
    ), [d, N, r, n, i, f, I]), Q = S((e) => e ? typeof e == "string" ? /* @__PURE__ */ l(
      he,
      {
        src: e,
        size: i,
        className: m.adorment,
        disabled: r
      }
    ) : fe.isValidElement(e) ? e : null : null, [r, i]), U = S((e) => {
      e.stopPropagation();
    }, []), X = S((e) => {
      e.stopPropagation();
    }, []), Z = () => {
      if (o == null || s && Array.isArray(o) && o.length === 0)
        return /* @__PURE__ */ l(Ee, { ownerState: { disabled: r, readOnly: n }, variant: "bodyStandard", color: "text.disabled", children: j });
      if (s) {
        if (!Array.isArray(o))
          return null;
        const e = o.map((t) => u.find((a) => a.id === t));
        return /* @__PURE__ */ l(
          _,
          {
            ref: x,
            ownerState: { ...d },
            className: m.renderValueContainer,
            children: e.map((t) => t ? /* @__PURE__ */ l(
              Ne,
              {
                size: i,
                label: t.label,
                description: t.description,
                startIcon: t.selectedStartAdornment ?? t.startAdornment,
                endIcon: t.endAdornment,
                opacity: !0,
                onDeleted: n || r ? void 0 : () => J(t),
                iconButtonProps: { onMouseDown: U, onKeyDown: X }
              },
              t.id
            ) : null)
          }
        );
      } else {
        const e = u.find((t) => String(t.id) === String(o));
        return e ? /* @__PURE__ */ oe(_, { ownerState: { ...d }, className: m.renderValueContainer, children: [
          (e.selectedStartAdornment ?? e.startAdornment) && Q(e.selectedStartAdornment ?? e.startAdornment),
          /* @__PURE__ */ l(Re, { ownerState: { disabled: r, readOnly: n }, variant: "bodyStandard", color: "text.primary", size: i, className: m.renderValueTypography, children: e.label })
        ] }) : "";
      }
    }, ee = S(() => {
      r || n || y(!0);
    }, [r, n]), te = S(() => {
      y(!1);
    }, []);
    V(() => {
      if (!s || !Array.isArray(o))
        return;
      const e = x.current;
      e && requestAnimationFrame(() => {
        e.scrollTop = e.scrollHeight;
      });
    }, [s, o]), V(() => {
      n && f && y(!1);
    }, [n, f]);
    const re = h(() => we(), []), ne = le(R, $);
    return Y ? /* @__PURE__ */ l(ye, { ownerState: { ...d }, className: m.skeletonSelect }) : /* @__PURE__ */ l(
      re,
      {
        ...v,
        ...ve(Me, xe.root, K),
        ref: ne,
        className: ue(m.root, m[g], B),
        ownerState: { ...d },
        IconComponent: P,
        multiple: s,
        value: o ?? (s ? [] : ""),
        onChange: G,
        fullWidth: !0,
        disabled: r,
        error: C,
        renderValue: Z,
        open: n ? !1 : f,
        native: !1,
        onOpen: ee,
        onClose: te,
        onClick: I,
        displayEmpty: !0,
        inputProps: {
          ...v.inputProps,
          readOnly: n
        },
        MenuProps: b,
        children: u.length > 0 ? u.map(
          (e) => {
            const t = s ? Array.isArray(o) && o.some((a) => a === e.id) : o === e.id;
            return /* @__PURE__ */ l(
              Ce,
              {
                className: m.menuItem,
                ownerState: { ...d },
                size: i,
                value: e.id,
                disabled: r,
                selected: t,
                label: e.label,
                description: e.description,
                startAdornment: e.startAdornment,
                endAdornment: e.endAdornment
              },
              String(e.id)
            );
          }
        ) : /* @__PURE__ */ l(
          ge,
          {
            ownerState: { ...d },
            className: m.menuItemNoOptions,
            size: i,
            label: q(pe.noOptions),
            disabled: !0
          }
        )
      }
    );
  }
);
export {
  qe as Select
};
