import { jsx, jsxs } from "react/jsx-runtime";
import { _ as __ } from "../../../default-i18n-CN_q3KUs.js";
import { BaseControl } from "../../base-control/base-control.js";
import { $ as $d2f53cda644affe3$export$2f2b9559550c7bbc, a as $440f4836bcb56932$export$b94867ecbd698f21 } from "../../../SearchField-jVsbJe1O.js";
import { $ as $d2b4bc8c273e7be6$export$353f5b6fc5456de1 } from "../../../Button-npzfSoYo.js";
import { $ as $3985021b0ad6602f$export$f5b8910cec6cf069 } from "../../../Input-ChJaTNa5.js";
import { $ as $01b77f81d0f07f68$export$b04be29aa201d4f5 } from "../../../Label-DWVaNd2E.js";
import { $ as $eed445e0843c11d0$export$41f133550aa26f48 } from "../../../ListBox-D0Stb4wr.js";
import { e as $07b14b47974efb58$export$5b6b19405a83ff9d } from "../../../Dialog-CQ8H6Noi.js";
import { $ as $82d7e5349645de74$export$ef9b1a59e592288f, a as $82d7e5349645de74$export$e288731fd71264f0, b as $82d7e5349645de74$export$ef445b55be0601bd } from "../../../Select-ciHB1pub.js";
import { useRef, useEffect, cloneElement, useContext } from "react";
import { icons } from "../../../icons/icons.js";
import "../../../react-jsx-parser.min-LF707GK8.js";
import { OptionItemBase } from "./shared.js";
import { RichLabel } from "../../rich-label/rich-label.js";
import { unescapeHTML } from "../../../utilities/text-helpers.js";
import { c as clsx } from "../../../utils-cvK1vxO7.js";
import { $ as $f86e6c1ec7da6ebb$export$bc3384a35de93d66 } from "../../../useAsyncList-D52mQcrH.js";
/**
 * Select menu with async loading.
 *
 * @component
 * @param {Object} props - Component props.
 * @param {string} [props.label] - Label of the component.
 * @param {string} [props.help] - Help text of the component.
 * @param {string} [props.icon] - Icon of the component.
 * @param {string} [props.subtitle] - Subtitle of the component.
 * @param {JSX.Element|JSX.Element[]} [props.actions] - Actions to show to the right of the label.
 * @param {boolean} [props.inline] - Whether the Select menu is displayed inline with the label, to the right.
 * @param {{label: string, value: string, metadata: Object<string, any>?}} props.value - Current value of the select.
 * @param {Function} props.onChange - Function to call when the value changes.
 * @param {boolean} [props.clearable=false] - Whether the select is clearable.
 * @param {boolean} [props.disabled=false] - Whether the select is disabled.
 * @param {string} [props.placeholder] - Placeholder text to show when no value is selected.
 * @param {Function} [props.getLabel] - Function to get the label for the item from the fetched data. `(item: Object<string, any>) => string`
 * @param {Function} [props.getValue] - Function to get the value for the item from the fetched data. `(item: Object<string, any>) => string`
 * @param {Function} [props.getMeta] - Function to get the metadata for the item from the fetched data. `(item: Object<string, any>) => Object<string, any>` (optional)
 * @param {Function} [props.getIcon] - Function to get the icon for the item from the fetched data. `(item: Object<string, any>) => JSX.Element | string`
 * @param {Function} [props.getSubtitle] - Function to get the subtitle for the item from the fetched data. `(item: Object<string, any>) => string`
 * @param {Function} [props.getData] - Function to pre-process the fetched data before it is used in the select. `(data: Object<string, any>[]) => Object<string, any>[]`
 * @param {Function} [props.fetchUrl] - Function to get the URL for fetching data. Provides typed search text if entered. `(searchText: string) => string`
 * @param {Object} [props.fetchConfig] - Configuration object for the fetch request, passed to the `fetch` function.
 * @param {Function} [props.fetchFunction] - Allows overriding the default fetch function. `fetchFunction: (url: string, fetchOptions: Object<string, any>, searchText?: string) => Promise<Object<string, any>>`
 * @param {Function} [props.processLoadedOptions] - Allows processing the options fetched from the source. `(options: Object<string, any>[]) => Object<string, any>[]`
 * @param {JSX.Element} [props.customMenuOption] - If provided, replaces the default item in the dropdown menu. `({ value: string, label: string, subtitle: string, metadata: any }) => JSX.Element`
 * @param {JSX.Element} [props.customValueDisplay] - If provided, replaces the default current value display of each selected item. `({ value: string, label: string, subtitle: string, metadata: any }) => JSX.Element`
 * @param {JSX.Element} [props.customDropdownArrow] - If provided, replaces the default dropdown arrow indicator.
 * @param {string} props.className - Classes to pass to the select menu.
 * @param {boolean} [props.noMinWidth=false] - If `true`, the select menu will not have a minimum width.
 * @param {boolean} [props.hidden] - If `true`, the component is not rendered.
 *
 * @returns {JSX.Element} The AsyncSelectNext component.
 *
 * @example
 * const [value, setValue] = useState(null);
 *
 * <AsyncSelectNext
 * 	label='Select items'
 * 	fetchUrl={(searchText) => `https://api.example.com/items?q=${searchText}`}
 * 	value={value}
 * 	onChange={setValue}
 * 	getLabel={(item) => item?.name}
 * 	getValue={(item) => item?.id}
 * />
 *
 * @preserve
 */
const AsyncSelectNext = (props) => {
  const {
    label,
    help,
    icon,
    subtitle,
    actions,
    inline,
    value,
    onChange,
    disabled = false,
    clearable = false,
    className,
    placeholder = __("Select...", "eightshift-ui-components"),
    customMenuOption,
    customValueDisplay,
    customDropdownArrow,
    processLoadedOptions = (options) => options,
    fetchUrl,
    fetchConfig = {},
    fetchFunction,
    getLabel = (item) => item?.label,
    getValue = (item) => item?.value,
    getMeta,
    getIcon,
    getSubtitle,
    getData = (data) => data,
    hidden,
    noMinWidth = false,
    ...rest
  } = props;
  const list = $f86e6c1ec7da6ebb$export$bc3384a35de93d66({
    getKey: (item) => item.value,
    async load({ signal, filterText }) {
      let json = [];
      if (fetchFunction) {
        const res = await fetchFunction(filterText, signal);
        json = processLoadedOptions ? processLoadedOptions(getData(res)) : getData(res);
      } else {
        const res = await fetch(fetchUrl(filterText), { ...fetchConfig, signal });
        json = processLoadedOptions ? processLoadedOptions(getData(await res.json())) : getData(res);
      }
      const output = json?.map((item, index) => {
        const id = getValue?.(item) ?? index;
        const entry = { label: unescapeHTML(getLabel?.(item) ?? ""), value: id };
        if (getMeta) {
          entry.meta = getMeta(item);
        }
        if (getSubtitle) {
          entry.subtitle = unescapeHTML(getSubtitle(item));
        }
        return entry;
      });
      if (value && value?.value && (filterText ?? "").length < 1 && output.length > 0 && !output?.find((item) => item.value === value?.value)) {
        return {
          items: [value, ...output.slice(0, -1)],
          selectedKeys: [value?.value]
        };
      }
      return {
        items: output
      };
    }
  });
  const ref = useRef();
  useEffect(() => {
    if (value?.value && !list.getItem(value?.value)) {
      list.items[0] = value;
    }
    list.setSelectedKeys(value?.value ? [value.value] : []);
    list.setFilterText("");
  }, [value?.value]);
  if (hidden) {
    return null;
  }
  return /* @__PURE__ */ jsx(
    $82d7e5349645de74$export$ef9b1a59e592288f,
    {
      isDisabled: disabled,
      selectedKey: value?.value ?? null,
      onSelectionChange: (selected) => {
        list.filterText = "";
        if (selected === null || selected === void 0) {
          onChange(null);
          return;
        }
        const item = list.items.find((item2) => item2.value === selected);
        if (!item) {
          onChange(null);
          return;
        }
        if (item && "id" in item) {
          delete item.id;
        }
        onChange(item);
      },
      placeholder,
      ...rest,
      children: /* @__PURE__ */ jsxs(
        BaseControl,
        {
          label,
          icon,
          subtitle,
          actions,
          help,
          inline,
          labelAs: $01b77f81d0f07f68$export$b04be29aa201d4f5,
          children: [
            /* @__PURE__ */ jsxs(
              "div",
              {
                className: clsx(
                  "es:relative es:flex es:items-center es:gap-1 es:px-1.5 es:focus-visible:outline-hidden es:focus-visible:ring-2 es:focus-visible:ring-accent-500/50",
                  "es:h-9 es:rounded-10 es:border es:border-secondary-300 es:bg-white es:text-sm es:shadow-sm es:transition",
                  "es:inset-ring es:inset-ring-secondary-100",
                  "es:any-focus:outline-hidden",
                  !noMinWidth && "es:min-w-48",
                  !inline && "es:w-full",
                  disabled && "es:select-none es:shadow-none!",
                  "es:has-[[aria-haspopup=listbox][data-focus-visible=true],[aria-autocomplete=list][data-focus-visible=true]]:border-accent-500 es:has-[[aria-haspopup=listbox][data-focus-visible=true],[aria-autocomplete=list][data-focus-visible=true]]:ring-2 es:has-[[aria-haspopup=listbox][data-focus-visible=true],[aria-autocomplete=list][data-focus-visible=true]]:ring-accent-500/50",
                  className
                ),
                ref,
                children: [
                  /* @__PURE__ */ jsxs($d2b4bc8c273e7be6$export$353f5b6fc5456de1, { className: "es:any-focus:outline-hidden es:text-start es:size-full es:inline-block es:group es:overflow-x-clip", children: [
                    /* @__PURE__ */ jsx($82d7e5349645de74$export$e288731fd71264f0, { children: ({ selectedItem }) => {
                      if (!value?.value) {
                        return /* @__PURE__ */ jsx("span", { className: "es:pointer-events-none es:pr-6 es:text-sm es:text-secondary-500", children: placeholder });
                      }
                      if (customValueDisplay) {
                        return customValueDisplay(selectedItem);
                      }
                      let icon2 = getIcon ? getIcon(selectedItem) : selectedItem?.icon ?? null;
                      if (typeof selectedItem?.icon === "string") {
                        icon2 = icons?.[selectedItem.icon] ?? null;
                      }
                      return /* @__PURE__ */ jsx(
                        RichLabel,
                        {
                          icon: icon2,
                          label: /* @__PURE__ */ jsx("span", { className: "es:line-clamp-1", children: selectedItem?.label }),
                          subtitle: /* @__PURE__ */ jsx("span", { className: "es:line-clamp-1", children: selectedItem?.subtitle }),
                          className: clsx("es:pr-6 es:grow es:w-full", disabled && "es:grayscale es:pointer-events-none"),
                          iconClassName: "es:pointer-events-none es:select-none"
                        }
                      );
                    } }),
                    /* @__PURE__ */ jsxs(
                      "div",
                      {
                        className: clsx("es:absolute es:bottom-0 es:right-1 es:top-0 es:my-auto es:flex es:items-center", disabled ? "es:text-secondary-300" : "es:text-secondary-500"),
                        "aria-hidden": "true",
                        children: [
                          !customDropdownArrow && cloneElement(icons.dropdownCaretAlt, {
                            className: "es:w-4 es:group-aria-expanded:-scale-y-100 es:transition-transform es:duration-200"
                          }),
                          customDropdownArrow && /* @__PURE__ */ jsx(
                            "div",
                            {
                              "aria-hidden": "true",
                              className: "es:group-aria-expanded:-scale-y-100 es:transition-transform es:duration-200",
                              children: customDropdownArrow
                            }
                          )
                        ]
                      }
                    )
                  ] }),
                  clearable && /* @__PURE__ */ jsx(SelectClearButton, {})
                ]
              }
            ),
            /* @__PURE__ */ jsx(
              $07b14b47974efb58$export$5b6b19405a83ff9d,
              {
                className: ({ isEntering, isExiting }) => clsx(
                  "es:flex es:w-76 es:min-w-9 es:max-w-76 es:flex-col es:overflow-hidden es:rounded-2xl es:border es:border-secondary-200 es:bg-white es:text-sm es:shadow-xl es:inset-ring es:inset-ring-secondary-100",
                  "es:any-focus:outline-hidden",
                  "es:motion-safe:motion-duration-200 es:motion-safe:motion-ease-spring-bouncy",
                  "es:placement-bottom:origin-top-left es:placement-top:origin-bottom-left",
                  "es:placement-left:origin-right es:placement-right:origin-left",
                  isEntering && "es:motion-safe:motion-scale-in-95 es:motion-opacity-in-0",
                  isEntering && "es:motion-safe:placement-top:motion-translate-y-in-[5%] es:motion-safe:placement-bottom:motion-translate-y-in-[-5%] es:motion-safe:placement-left:motion-translate-x-in-[5%] es:motion-safe:placement-right:motion-translate-x-in-[-5%]",
                  isExiting && "es:motion-safe:motion-scale-out-95 es:motion-opacity-out-0",
                  isExiting && "es:motion-safe:placement-top:motion-translate-y-out-[5%] es:motion-safe:placement-bottom:motion-translate-y-out-[-5%] es:motion-safe:placement-left:motion-translate-x-out-[5%] es:motion-safe:placement-right:motion-translate-x-out-[-5%]"
                ),
                placement: "bottom left",
                maxHeight: 300,
                triggerRef: ref,
                children: /* @__PURE__ */ jsxs(
                  $d2f53cda644affe3$export$2f2b9559550c7bbc,
                  {
                    inputValue: list.filterText,
                    onInputChange: list.setFilterText,
                    children: [
                      /* @__PURE__ */ jsxs(
                        $440f4836bcb56932$export$b94867ecbd698f21,
                        {
                          "aria-label": __("Search", "eightshift-ui-components"),
                          className: "es:flex es:items-center es:bg-secondary-100 es:m-2 es:rounded-lg es:relative es:placeholder:text-secondary-500",
                          autoFocus: true,
                          children: [
                            /* @__PURE__ */ jsx(
                              $3985021b0ad6602f$export$f5b8910cec6cf069,
                              {
                                placeholder: __("Search...", "eightshift-ui-components"),
                                className: "es:peer es:size-full es:h-9 es:outline-hidden es:shadow-none es:px-2.5 es:text-sm es:py-0 es:[&::-webkit-search-cancel-button]:hidden"
                              }
                            ),
                            /* @__PURE__ */ jsx(
                              $d2b4bc8c273e7be6$export$353f5b6fc5456de1,
                              {
                                "aria-label": __("Clear", "eightshift-ui-components"),
                                className: clsx(
                                  "es:absolute es:right-2 es:top-0 es:bottom-0 es:my-auto",
                                  "es:flex es:size-6 es:items-center es:justify-center es:rounded es:text-sm es:text-secondary-600 es:transition es:hover:bg-red-50 es:hover:text-red-900 es:any-focus:outline-hidden es:focus:ring-2 es:focus:ring-accent-500/50 es:disabled:text-secondary-300 es:cursor-pointer",
                                  "es:peer-placeholder-shown:opacity-0"
                                ),
                                children: icons.clearAlt
                              }
                            )
                          ]
                        }
                      ),
                      /* @__PURE__ */ jsx("div", { className: "es:w-full es:h-px es:bg-secondary-200 es:shrink-0" }),
                      list.isLoading && /* @__PURE__ */ jsx("div", { className: "es:p-3 es:min-h-16 es:flex es:items-center es:justify-center", children: cloneElement(icons.loader, { className: "es:text-accent-600! es:size-5 es:motion-preset-spin es:motion-duration-1500" }) }),
                      /* @__PURE__ */ jsx(
                        $eed445e0843c11d0$export$41f133550aa26f48,
                        {
                          className: clsx("es:space-y-0.5 es:p-1 es:any-focus:outline-hidden es:min-h-16", list.isLoading && "es:hidden", list?.items?.length > 0 && "es:overflow-y-auto"),
                          items: list.items,
                          renderEmptyState: () => /* @__PURE__ */ jsx(
                            RichLabel,
                            {
                              icon: icons.searchEmpty,
                              label: __("No results", "eightshift-ui-components"),
                              subtitle: __("Try a different search term", "eightshift-ui-components"),
                              className: "es:min-h-14 es:p-2 es:w-fit es:mx-auto es:motion-preset-slide-up es:motion-ease-spring-bouncy es:motion-duration-200 es:shrink-0",
                              iconClassName: "es:text-accent-700 es:icon:size-7!",
                              noColor: true
                            }
                          ),
                          children: (item) => {
                            let icon2 = getIcon ? getIcon(item) : item?.icon ?? null;
                            if (typeof item?.icon === "string") {
                              icon2 = icons?.[item.icon] ?? null;
                            }
                            return /* @__PURE__ */ jsxs(
                              OptionItemBase,
                              {
                                id: item?.value,
                                className: item?.className,
                                children: [
                                  customMenuOption && customMenuOption(item),
                                  !customMenuOption && /* @__PURE__ */ jsx(
                                    RichLabel,
                                    {
                                      icon: icon2,
                                      label: item?.label,
                                      subtitle: item?.subtitle,
                                      noColor: true
                                    }
                                  )
                                ]
                              }
                            );
                          }
                        }
                      )
                    ]
                  }
                )
              }
            )
          ]
        }
      )
    }
  );
};
const SelectClearButton = () => {
  const state = useContext($82d7e5349645de74$export$ef445b55be0601bd);
  const isEmpty = state?.selectedKey === null;
  return /* @__PURE__ */ jsx(
    $d2b4bc8c273e7be6$export$353f5b6fc5456de1,
    {
      "aria-label": __("Clear value", "eightshift-ui-components"),
      className: clsx(
        "es:mr-6 es:flex es:h-6 es:w-8 es:items-center es:justify-center es:rounded es:text-sm es:text-secondary-600 es:transition es:hover:bg-red-50 es:hover:text-red-900 es:any-focus:outline-hidden es:focus:ring-2 es:focus:ring-accent-500/50 es:disabled:text-secondary-300 es:cursor-pointer",
        isEmpty ? "es:hidden" : "es:flex"
      ),
      onPress: () => state?.setSelectedKey(null),
      slot: null,
      children: icons.clearAlt
    }
  );
};
export {
  AsyncSelectNext
};
