import { jsx, jsxs } from "react/jsx-runtime";
/* empty css                 */
import { forwardRef, useState, useEffect, useImperativeHandle } from "react";
import { ChatAvatar } from "../TableChatRightSection/AvatarGroup/AvatarGroup.js";
const MentionList = forwardRef((props, ref) => {
  var _a;
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const selectItem = (index) => {
    const item = props.items[index];
    if (item) {
      props.command({
        id: item.id,
        label: item.name
      });
    }
  };
  const upHandler = () => {
    if (props.items.length === 0) return;
    setSelectedIndex((selectedIndex + props.items.length - 1) % props.items.length);
  };
  const downHandler = () => {
    if (props.items.length === 0) return;
    setSelectedIndex((selectedIndex + 1) % props.items.length);
  };
  const enterHandler = () => {
    selectItem(selectedIndex);
  };
  useEffect(() => {
    setSelectedIndex(0);
  }, [props.items]);
  useEffect(() => {
    if (props.items && typeof props.items.then === "function") {
      setIsLoading(true);
      props.items.finally(() => {
        setIsLoading(false);
      });
    }
  }, [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;
    }
  }));
  if (isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "dropdown-menu", children: /* @__PURE__ */ jsxs("div", { className: "mention-loading", children: [
      /* @__PURE__ */ jsx("div", { className: "loading-spinner" }),
      /* @__PURE__ */ jsx("span", { children: "Loading users..." })
    ] }) });
  }
  return /* @__PURE__ */ jsx("div", { className: "dropdown-menu", children: ((_a = props.items) == null ? void 0 : _a.length) ? props.items.map((item, index) => /* @__PURE__ */ jsxs(
    "button",
    {
      className: `mention-item ${index === selectedIndex ? "is-selected" : ""}`,
      onClick: () => {
        selectItem(index);
      },
      children: [
        /* @__PURE__ */ jsx("div", { className: "mention-avatar", children: /* @__PURE__ */ jsx(ChatAvatar, { name: item.name, size: "sm", src: item.avatar }) }),
        /* @__PURE__ */ jsxs("div", { className: "mention-info", children: [
          /* @__PURE__ */ jsx("span", { className: "mention-name", children: item == null ? void 0 : item.name }),
          item.status && /* @__PURE__ */ jsx("span", { className: "mention-status", children: item.status })
        ] })
      ]
    },
    item.id || index
  )) : /* @__PURE__ */ jsx("div", { className: "mention-no-result", children: "No users found" }) });
});
export {
  MentionList
};
