import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, forwardRef, useRef, useImperativeHandle } from "react";
import { Text } from "ink";
import { serverRegistry } from "@dexto/registry";
import { BaseSelector } from "../base/BaseSelector.js";
const McpAddSelector = forwardRef(
  function McpAddSelector2({ isVisible, onSelect, onClose }, ref) {
    const baseSelectorRef = useRef(null);
    useImperativeHandle(
      ref,
      () => ({
        handleInput: (input, key) => {
          return baseSelectorRef.current?.handleInput(input, key) ?? false;
        }
      }),
      []
    );
    const [options, setOptions] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [selectedIndex, setSelectedIndex] = useState(0);
    useEffect(() => {
      if (!isVisible) return;
      let cancelled = false;
      setIsLoading(true);
      const fetchEntries = async () => {
        try {
          const entries = await serverRegistry.getEntries();
          if (cancelled) return;
          const availablePresets = entries.filter((e) => !e.isInstalled);
          const optionList = availablePresets.map((entry) => ({
            id: entry.id,
            label: entry.name,
            description: entry.description,
            icon: entry.icon || "\u{1F4E6}",
            entry
          }));
          setOptions(optionList);
          setSelectedIndex(0);
        } catch {
          if (!cancelled) {
            setOptions([]);
          }
        } finally {
          if (!cancelled) {
            setIsLoading(false);
          }
        }
      };
      void fetchEntries();
      return () => {
        cancelled = true;
      };
    }, [isVisible]);
    const formatItem = (option, isSelected) => /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs(Text, { children: [
        option.icon,
        " "
      ] }),
      /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "gray", bold: isSelected, children: option.label }),
      /* @__PURE__ */ jsxs(Text, { color: isSelected ? "white" : "gray", children: [
        " ",
        "- ",
        option.description.slice(0, 40),
        option.description.length > 40 ? "..." : ""
      ] })
    ] });
    const handleSelect = (option) => {
      onSelect({ type: "preset", entry: option.entry });
    };
    return /* @__PURE__ */ jsx(
      BaseSelector,
      {
        ref: baseSelectorRef,
        items: options,
        isVisible,
        isLoading,
        selectedIndex,
        onSelectIndex: setSelectedIndex,
        onSelect: handleSelect,
        onClose,
        formatItem,
        title: "Add MCP Server (Presets)",
        borderColor: "green",
        loadingMessage: "Loading server presets...",
        emptyMessage: "No server presets available"
      }
    );
  }
);
var McpAddSelector_default = McpAddSelector;
export {
  McpAddSelector_default as default
};
