import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { useState, useRef, useLayoutEffect, useMemo } from "react";
import { IconSearchLg } from "../../icons/index.mjs";
/* empty css                                                                                                                                                                                       */
/* empty css                                                                                                                                                                                        */
/* empty css                                                                                                                                                                                                */
/* empty css                                                                                                                                                                                           */
/* empty css                                                                                                                                                                                           */
import { isValueChecked } from "./helper.mjs";
import { useProps } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/core/MantineProvider/use-props/use-props.mjs";
import { useMantineTheme } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs";
import { useCombobox } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/use-combobox/use-combobox.mjs";
import { useUncontrolled } from "../../node_modules/.pnpm/@mantine_hooks@7.15.2_react@18.3.1/node_modules/@mantine/hooks/esm/use-uncontrolled/use-uncontrolled.mjs";
import { getParsedComboboxData } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/get-parsed-combobox-data/get-parsed-combobox-data.mjs";
import { getOptionsLockup } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/get-options-lockup/get-options-lockup.mjs";
import { defaultOptionsFilter } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/OptionsDropdown/default-options-filter.mjs";
import { Pill } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Pill/Pill.mjs";
import { isOptionsGroup } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/OptionsDropdown/is-options-group.mjs";
import { Combobox } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/Combobox.mjs";
import { Group } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Group/Group.mjs";
import { Checkbox } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Checkbox/Checkbox.mjs";
import { Box } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/core/Box/Box.mjs";
import { Divider } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Divider/Divider.mjs";
import { InputBase } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/InputBase/InputBase.mjs";
import { Loader } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Loader/Loader.mjs";
import { Input } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Input/Input.mjs";
import { ScrollArea } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/ScrollArea/ScrollArea.mjs";
const Option = ({ data, withCheckIcon, value, checkIconPosition, unstyled, renderOption }) => {
  if (!isOptionsGroup(data)) {
    const checked = isValueChecked(value, data.value);
    const check = withCheckIcon && /* @__PURE__ */ jsx(Checkbox, { size: "xs", checked, "aria-checked": checked, readOnly: true });
    const defaultContent = /* @__PURE__ */ jsxs(Group, { children: [
      checkIconPosition === "left" && check,
      /* @__PURE__ */ jsx(Box, { sx: { flex: 1 }, children: data.label }),
      checkIconPosition === "right" && check
    ] });
    return /* @__PURE__ */ jsx(
      Combobox.Option,
      {
        value: data.value,
        disabled: data.disabled,
        "data-reverse": checkIconPosition === "right" || void 0,
        "data-checked": checked || void 0,
        "aria-selected": checked,
        active: checked,
        styles: (theme) => ({
          option: {
            "&:hover": {
              backgroundColor: theme.colors.carbon[3]
            }
          }
        }),
        children: typeof renderOption === "function" ? renderOption({ option: data, checked }) : defaultContent
      }
    );
  }
  const options = data.items.map((item) => /* @__PURE__ */ jsx(
    Option,
    {
      data: item,
      value,
      unstyled,
      withCheckIcon,
      checkIconPosition,
      renderOption
    },
    item.value
  ));
  return /* @__PURE__ */ jsx(Combobox.Group, { label: data.group, children: options });
};
const defaultProps = {
  maxValues: Infinity,
  withCheckIcon: true,
  checkIconPosition: "left",
  hiddenInputValuesDivider: ","
};
const ValuesVisible = ({ moreCount, readOnly, values, disabled, onRemove, optionsLockup }) => {
  const containerRef = useRef(null);
  const [valsVisible, setValsVisible] = useState(values);
  const [moreVisible, setMoreVisible] = useState(moreCount);
  const [isLongFirstOverflow, setIsLongFirstOverflow] = useState(false);
  const isCheckOverflowEnd = useRef(false);
  useLayoutEffect(() => {
    const container = containerRef.current;
    if (!container) {
      return;
    }
    const resizeObserver = new ResizeObserver(() => {
      isCheckOverflowEnd.current = false;
      setValsVisible(values);
      setMoreVisible(moreCount);
    });
    resizeObserver.observe(container);
    return () => resizeObserver.unobserve(container);
  }, [values, moreCount]);
  useLayoutEffect(() => {
    const container = containerRef.current;
    if (!container || isCheckOverflowEnd.current) {
      return;
    }
    const isOverflow = container.scrollWidth > container.clientWidth;
    if (isOverflow) {
      if (valsVisible.length === 1) {
        isCheckOverflowEnd.current = true;
        setIsLongFirstOverflow(true);
        return;
      }
      const newValsVisible = valsVisible.slice(0, -1);
      const newMoreVisible = moreVisible + 1;
      setValsVisible(newValsVisible);
      setMoreVisible(newMoreVisible);
    } else if (!isOverflow && isLongFirstOverflow) {
      setIsLongFirstOverflow(false);
    } else {
      isCheckOverflowEnd.current = true;
    }
  }, [valsVisible, moreVisible, isLongFirstOverflow]);
  return /* @__PURE__ */ jsxs(
    Pill.Group,
    {
      mah: 22,
      sx: {
        display: "flex",
        flexWrap: "nowrap",
        overflow: "hidden"
      },
      ref: containerRef,
      children: [
        valsVisible.map((item, index) => {
          var _a, _b;
          return /* @__PURE__ */ jsx(
            Pill,
            {
              withRemoveButton: !readOnly && !((_a = optionsLockup[item]) == null ? void 0 : _a.disabled),
              onRemove: () => {
                onRemove(item);
              },
              disabled,
              styles: (theme) => ({
                root: {
                  backgroundColor: theme.colors.carbon[3],
                  borderRadius: theme.radius.sm,
                  // if the first item is too long, we need to set flex: 1 and minWidth: 0 to make it shrink
                  flex: isLongFirstOverflow ? "1" : void 0,
                  minWidth: isLongFirstOverflow ? 0 : void 0
                }
              }),
              children: ((_b = optionsLockup[item]) == null ? void 0 : _b.label) || item
            },
            `${item}-${index}`
          );
        }),
        /* @__PURE__ */ jsxs(
          Pill,
          {
            styles: (theme) => ({
              root: {
                backgroundColor: theme.colors.carbon[3],
                borderRadius: theme.radius.sm,
                display: moreCount > 0 ? "block" : "none",
                opacity: moreVisible > 0 ? 1 : 0,
                flexShrink: 0
              }
            }),
            children: [
              "+",
              moreVisible
            ]
          }
        )
      ]
    }
  );
};
const ProMultiSelect = (_props) => {
  const props = useProps("MultiSelect", defaultProps, _props);
  const {
    data,
    value,
    defaultValue,
    limit,
    searchable,
    searchValue,
    defaultSearchValue,
    maxValues,
    readOnly,
    disabled,
    size,
    width,
    selectFirstOptionOnChange,
    placeholder,
    clearable,
    label,
    nothingFoundMessage,
    dropdownOpened,
    defaultDropdownOpened,
    loading,
    maxDropdownHeight,
    error,
    allowSelectAll,
    selectAllText,
    onOptionSubmit,
    renderOption,
    filter,
    onChange,
    onSearchChange,
    onRemove,
    onClear
  } = props;
  const theme = useMantineTheme();
  const combobox = useCombobox({
    opened: dropdownOpened,
    defaultOpened: defaultDropdownOpened,
    onDropdownClose: () => {
      combobox.resetSelectedOption();
      setSearchValue("");
    },
    onDropdownOpen: () => {
      combobox.focusSearchInput();
    }
  });
  const [_value, setValue] = useUncontrolled({
    value,
    defaultValue,
    finalValue: [],
    onChange
  });
  const [_searchValue, setSearchValue] = useUncontrolled({
    value: searchValue,
    defaultValue: defaultSearchValue,
    finalValue: "",
    onChange: onSearchChange
  });
  const parsedData = getParsedComboboxData(data);
  const optionsLockup = getOptionsLockup(parsedData);
  const shouldFilter = typeof _searchValue === "string";
  const filteredData = shouldFilter ? (filter || defaultOptionsFilter)({
    options: parsedData,
    search: searchable ? _searchValue : "",
    limit: limit ?? Infinity
  }) : parsedData;
  const [targetIndex, setTargetIndex] = useState(-1);
  const valuesForCompute = _value.map((item, index) => {
    var _a, _b;
    return /* @__PURE__ */ jsx(
      Pill,
      {
        withRemoveButton: !readOnly && !((_a = optionsLockup[item]) == null ? void 0 : _a.disabled),
        onRemove: () => {
          setValue(_value.filter((i) => item !== i));
          onRemove == null ? void 0 : onRemove(item);
        },
        disabled,
        styles: (theme2) => ({ root: { backgroundColor: theme2.colors.carbon[3], borderRadius: theme2.radius.sm } }),
        children: ((_b = optionsLockup[item]) == null ? void 0 : _b.label) || item
      },
      `${item}-${index}`
    );
  });
  const inputRef = useRef(null);
  useLayoutEffect(() => {
    var _a;
    const child = (_a = inputRef.current) == null ? void 0 : _a.children;
    if (!child || (child == null ? void 0 : child.length) <= 1) {
      return;
    }
    const firstOffsetLeft = child[0].offsetLeft;
    const index = Array.from(child).findIndex(
      (child2, idx) => child2.offsetLeft === firstOffsetLeft && idx > 0
    );
    setTargetIndex(index);
  }, [_value]);
  const options = filteredData == null ? void 0 : filteredData.map((item) => /* @__PURE__ */ jsx(
    Option,
    {
      data: item,
      value: _value,
      unstyled: false,
      withCheckIcon: true,
      checkIconPosition: "left",
      renderOption
    },
    isOptionsGroup(item) ? item.group : item.value
  ));
  const allChecked = useMemo(() => {
    return parsedData.every((value2) => {
      if (isOptionsGroup(value2)) {
        return value2.items.every((item) => _value.includes(item.value));
      } else {
        return _value.includes(value2.value);
      }
    });
  }, [parsedData, _value]);
  const indeterminate = _value.length > 0 && !allChecked;
  const selectAll = /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      Combobox.Option,
      {
        value: "_select_all",
        "data-checked": allChecked,
        "aria-selected": allChecked,
        active: allChecked,
        styles: (theme2) => ({
          option: {
            "&:hover": {
              backgroundColor: theme2.colors.carbon[3]
            }
          }
        }),
        children: /* @__PURE__ */ jsxs(Group, { children: [
          /* @__PURE__ */ jsx(Checkbox, { size: "xs", checked: allChecked, indeterminate, "aria-checked": allChecked, readOnly: true }),
          /* @__PURE__ */ jsx(Box, { sx: { flex: 1 }, children: selectAllText || "All" })
        ] })
      }
    ),
    /* @__PURE__ */ jsx(Divider, { color: "carbon.3" })
  ] });
  const handleOptionSubmit = (val) => {
    if (val === "_select_all") {
      if (allChecked) {
        setValue([]);
      } else {
        const allValues = parsedData.reduce((acc, value2) => {
          if (isOptionsGroup(value2)) {
            return [...acc, ...value2.items.map((item) => item.value)];
          } else {
            return [...acc, value2.value];
          }
        }, []);
        setValue(allValues);
      }
    } else {
      onOptionSubmit == null ? void 0 : onOptionSubmit(val);
      setSearchValue("");
      combobox.updateSelectedOptionIndex("selected");
      if (_value.includes(optionsLockup[val].value)) {
        setValue(_value.filter((v) => v !== optionsLockup[val].value));
        onRemove == null ? void 0 : onRemove(optionsLockup[val].value);
      } else if (_value.length < maxValues) {
        setValue([..._value, optionsLockup[val].value]);
      }
    }
  };
  const clearButton = /* @__PURE__ */ jsx(
    Combobox.ClearButton,
    {
      onClear: () => {
        onClear == null ? void 0 : onClear();
        setValue([]);
        setSearchValue("");
      }
    }
  );
  const _clearable = clearable && _value.length > 0 && !disabled && !readOnly;
  const moreCount = targetIndex > 0 ? _value.length - targetIndex : 0;
  return /* @__PURE__ */ jsxs(
    Combobox,
    {
      store: combobox,
      withinPortal: true,
      size,
      readOnly,
      onOptionSubmit: handleOptionSubmit,
      shadow: "sm",
      styles: {
        search: {
          borderRadius: theme.radius.md
        }
      },
      children: [
        /* @__PURE__ */ jsx(Combobox.Target, { children: /* @__PURE__ */ jsxs(
          InputBase,
          {
            error,
            w: width,
            component: "button",
            type: "button",
            pointer: true,
            disabled: disabled || loading,
            rightSection: loading ? /* @__PURE__ */ jsx(Loader, { size: "sm" }) : _clearable ? clearButton : /* @__PURE__ */ jsx(Combobox.Chevron, {}),
            label,
            styles: {
              label: { color: theme.colors.carbon[8], marginBottom: 6, fontSize: 14, lineHeight: "20px" },
              description: { color: theme.colors.carbon[6] },
              error: { color: theme.colors.red[7] }
            },
            rightSectionPointerEvents: value === null ? "none" : "all",
            onClick: () => combobox.toggleDropdown(),
            children: [
              _value.length === 0 && !!placeholder && /* @__PURE__ */ jsx(Input.Placeholder, { children: placeholder }),
              /* @__PURE__ */ jsx(
                Pill.Group,
                {
                  ref: inputRef,
                  mah: 22,
                  sx: {
                    flexWrap: "wrap",
                    overflowY: "clip",
                    maxWidth: "100%",
                    opacity: 0,
                    pointerEvents: "none",
                    height: 0
                  },
                  children: valuesForCompute
                }
              ),
              // _value.length > 0 is required. Because this component need a render cycle to synchronize props to state. So if we remove '_value.length > 0', when we uncheck the last item, the placeholder will show, but at that moment, the state in this ValuesVisible component keeps previous values
              _value.length > 0 && /* @__PURE__ */ jsx(
                ValuesVisible,
                {
                  disabled,
                  readOnly,
                  optionsLockup,
                  moreCount,
                  values: _value.slice(0, targetIndex > 0 ? targetIndex : _value.length),
                  onRemove: (item) => {
                    setValue(_value.filter((i) => item !== i));
                    onRemove == null ? void 0 : onRemove(item);
                  }
                }
              )
            ]
          }
        ) }),
        /* @__PURE__ */ jsxs(Combobox.Dropdown, { children: [
          searchable && /* @__PURE__ */ jsx(
            Combobox.Search,
            {
              leftSection: /* @__PURE__ */ jsx(IconSearchLg, { size: 16, c: "gray.9", strokeWidth: 2 }),
              value: _searchValue,
              onChange: (event) => {
                setSearchValue(event.currentTarget.value);
                searchable && combobox.openDropdown();
                selectFirstOptionOnChange && combobox.selectFirstOption();
              },
              placeholder: "Find"
            }
          ),
          /* @__PURE__ */ jsxs(ScrollArea.Autosize, { type: "scroll", mah: maxDropdownHeight ?? 200, children: [
            allowSelectAll && selectAll,
            /* @__PURE__ */ jsx(Combobox.Options, { children: options.length > 0 ? options : /* @__PURE__ */ jsx(Combobox.Empty, { children: nothingFoundMessage || "Nothing found" }) })
          ] })
        ] })
      ]
    }
  );
};
export {
  ProMultiSelect
};
