import {
  isLoqateErrorResponse
} from "./chunk-66ARYOY7.js";
import {
  Combobox
} from "./chunk-XEP6X7JU.js";
import {
  Icon
} from "./chunk-TKIP5Q5H.js";

// src/components/AddressLookup/AddressLookup.tsx
import { search } from "@simplybusiness/icons";
import { useCallback, useState } from "react";
import { jsx } from "react/jsx-runtime";
function optionsFromResponse({ Items }, addressLookupService) {
  if (!Items || !Array.isArray(Items)) {
    throw Error("No address found");
  }
  if (isLoqateErrorResponse(Items)) {
    throw Error(Items[0].Description);
  }
  return Items.map((item) => ({
    id: item.Id,
    label: `${item.Text}, ${item.Description}`,
    value: item.Text,
    // Add a callback to trigger secondary search
    // if the address type is not "Address"
    callback: item.Type === "Address" ? void 0 : async () => {
      const result = await addressLookupService.findById(item.Id);
      return optionsFromResponse(result, addressLookupService);
    }
  }));
}
var AddressLookup = ({
  ref,
  addressLookupService,
  onAddressSelected,
  onOptionsDisplayed,
  onError,
  errorMessage,
  ...otherProps
}) => {
  const [error, _setError] = useState(null);
  const setError = useCallback(
    (newError) => {
      if (newError != null) onError?.(newError);
      _setError(newError);
    },
    [onError]
  );
  const asyncOptions = useCallback(
    async (searchTerm) => {
      try {
        const response = await addressLookupService.search(searchTerm);
        setError(null);
        const options = optionsFromResponse(response, addressLookupService);
        onOptionsDisplayed?.();
        return options;
      } catch (e) {
        setError(e);
        return [];
      }
    },
    [addressLookupService, setError, onOptionsDisplayed]
  );
  const handleSelected = (selected) => {
    setError(null);
    const isEmpty = typeof selected === "string" ? selected === "" : !selected.id && !selected.value;
    if (isEmpty) {
      return Promise.resolve();
    }
    if (typeof selected === "string" || !selected.id) {
      setError(new Error("Selected option missing id"));
      return Promise.resolve();
    }
    return addressLookupService.get(selected.id).then(onAddressSelected).catch(setError);
  };
  const realErrorMessage = error && "An error occurred" || errorMessage;
  return /* @__PURE__ */ jsx(
    Combobox,
    {
      ...otherProps,
      ref,
      onSelected: handleSelected,
      asyncOptions,
      errorMessage: realErrorMessage,
      icon: /* @__PURE__ */ jsx(Icon, { icon: search })
    }
  );
};
AddressLookup.displayName = "AddressLookup";

export {
  AddressLookup
};
//# sourceMappingURL=chunk-QNOBB5HT.js.map
