import { j as jsxRuntimeExports } from "../../../../../_virtual/jsx-runtime.js";
import { forwardRef, useState, useEffect, useImperativeHandle } from "react";
import { tx as D } from "../../../../style-system/dist/twind.js";
const DatasourceFieldList = forwardRef((props, ref) => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const selectItem = (index) => {
    const item = props.items[index];
    if (item) {
      props.command({ id: item });
    }
  };
  const upHandler = () => {
    const newIndex = (selectedIndex + props.items.length - 1) % props.items.length;
    setSelectedIndex(newIndex);
    document.querySelector(`[data-ds-id="${newIndex}"]`)?.scrollIntoView({ behavior: "smooth", block: "nearest" });
  };
  const downHandler = () => {
    const newIndex = (selectedIndex + 1) % props.items.length;
    setSelectedIndex(newIndex);
    document.querySelector(`[data-ds-id="${newIndex}"]`)?.scrollIntoView({ behavior: "smooth", block: "nearest" });
  };
  const enterHandler = () => {
    selectItem(selectedIndex);
  };
  useEffect(() => setSelectedIndex(0), [props.items]);
  useImperativeHandle(ref, () => ({
    onKeyDown: ({ event }) => {
      if (event.key === "ArrowUp") {
        upHandler();
        return true;
      }
      if (event.key === "ArrowDown") {
        downHandler();
        return true;
      }
      if (event.key === "Enter") {
        enterHandler();
        return true;
      }
      return false;
    }
  }));
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      className: D(
        "bg-white l border border-gray-200 rounded-lg shadow-lg min-w-[280px] flex flex-col gap-0.5 max-h-[200px] overflow-auto p-2 z-auto"
      ),
      children: props.items.length ? props.items.map((item, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          "data-ds-id": index,
          type: "button",
          className: D(
            index === selectedIndex ? "bg-upstart-100" : "hover:bg-upstart-50",
            "flex font-light text-sm text-left w-full items-center px-2 py-1 rounded"
          ),
          onClick: () => selectItem(index),
          children: item
        },
        index
      )) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "item text-sm", children: "No match" })
    }
  );
});
export {
  DatasourceFieldList as default
};
//# sourceMappingURL=DatasourceFieldList.js.map
