import { jsx, jsxs } from "react/jsx-runtime";
import {
  useState,
  useEffect,
  forwardRef,
  useRef,
  useImperativeHandle,
  useMemo
} from "react";
import { Box, Text } from "ink";
import {
  listMarketplaces,
  listAllMarketplacePlugins,
  installPluginFromMarketplace,
  getUninstalledDefaults,
  addMarketplace,
  listInstalledPlugins
} from "@dexto/agent-management";
import { logger } from "@dexto/core";
import { BaseSelector } from "../base/BaseSelector.js";
function getSourceIcon(type) {
  switch (type) {
    case "github":
      return "\u{1F419}";
    case "git":
      return "\u{1F4E6}";
    case "local":
      return "\u{1F4C1}";
    default:
      return "\u{1F4E6}";
  }
}
const MarketplaceBrowser = forwardRef(
  function MarketplaceBrowser2({ isVisible, onAction, onClose }, ref) {
    const baseSelectorRef = useRef(null);
    const [selectedIndex, setSelectedIndex] = useState(0);
    const [isLoading, setIsLoading] = useState(true);
    const [loadError, setLoadError] = useState(null);
    const [view, setView] = useState("marketplaces");
    const [marketplaces, setMarketplaces] = useState([]);
    const [plugins, setPlugins] = useState([]);
    const [selectedMarketplace, setSelectedMarketplace] = useState(null);
    const [isInstalling, setIsInstalling] = useState(false);
    const [uninstalledDefaults, setUninstalledDefaults] = useState([]);
    const [pendingPlugin, setPendingPlugin] = useState(null);
    const [installedPluginNames, setInstalledPluginNames] = useState(/* @__PURE__ */ new Set());
    useImperativeHandle(
      ref,
      () => ({
        handleInput: (input, key) => {
          return baseSelectorRef.current?.handleInput(input, key) ?? false;
        }
      }),
      []
    );
    useEffect(() => {
      if (isVisible) {
        loadMarketplaces();
      }
    }, [isVisible]);
    const loadMarketplaces = () => {
      setIsLoading(true);
      setLoadError(null);
      setView("marketplaces");
      setSelectedMarketplace(null);
      setSelectedIndex(0);
      try {
        const mktplaces = listMarketplaces();
        setMarketplaces(mktplaces);
        const allPlugins = listAllMarketplacePlugins();
        setPlugins(allPlugins);
        const defaults = getUninstalledDefaults();
        setUninstalledDefaults(defaults);
        const installed = listInstalledPlugins();
        setInstalledPluginNames(new Set(installed.map((p) => p.name.toLowerCase())));
      } catch (error) {
        setLoadError(
          `Failed to load: ${error instanceof Error ? error.message : String(error)}`
        );
        setMarketplaces([]);
        setPlugins([]);
        setUninstalledDefaults([]);
        setInstalledPluginNames(/* @__PURE__ */ new Set());
      } finally {
        setIsLoading(false);
      }
    };
    const showMarketplacePlugins = (marketplaceName) => {
      setSelectedMarketplace(marketplaceName);
      setView("plugins");
      setSelectedIndex(0);
    };
    const goBackToMarketplaces = () => {
      setView("marketplaces");
      setSelectedMarketplace(null);
      setSelectedIndex(0);
    };
    const showScopeSelection = (plugin) => {
      setPendingPlugin(plugin);
      setView("scope-select");
      setSelectedIndex(0);
    };
    const goBackToPlugins = () => {
      setPendingPlugin(null);
      setView("plugins");
      setSelectedIndex(0);
    };
    const items = useMemo(() => {
      if (view === "marketplaces") {
        const list = [];
        list.push({ type: "back" });
        for (const def of uninstalledDefaults) {
          list.push({
            type: "default-marketplace",
            name: def.name,
            sourceValue: def.source.value,
            sourceType: def.source.type
          });
        }
        for (const m of marketplaces) {
          const pluginCount = plugins.filter((p) => p.marketplace === m.name).length;
          list.push({
            type: "marketplace",
            marketplace: m,
            pluginCount
          });
        }
        list.push({ type: "add-new" });
        return list;
      } else if (view === "scope-select") {
        const list = [{ type: "back" }];
        list.push({
          type: "scope",
          scope: "user",
          label: "Global (user)",
          description: "Available in all projects",
          icon: "\u{1F310}"
        });
        list.push({
          type: "scope",
          scope: "project",
          label: "Project only",
          description: "Only in current project, can be committed to git",
          icon: "\u{1F4C1}"
        });
        return list;
      } else {
        const filteredPlugins = selectedMarketplace ? plugins.filter((p) => p.marketplace === selectedMarketplace) : plugins;
        const list = [{ type: "back" }];
        for (const plugin of filteredPlugins) {
          const isInstalled = installedPluginNames.has(plugin.name.toLowerCase());
          list.push({
            type: "plugin",
            plugin,
            isInstalled
          });
        }
        return list;
      }
    }, [
      view,
      marketplaces,
      plugins,
      selectedMarketplace,
      uninstalledDefaults,
      installedPluginNames
    ]);
    const formatItem = (item, isSelected) => {
      if (item.type === "back") {
        const label = view === "scope-select" ? "Back to plugins" : view === "plugins" ? "Back to marketplaces" : "Back to menu";
        return /* @__PURE__ */ jsxs(Box, { children: [
          /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
          /* @__PURE__ */ jsx(Text, { color: "gray", children: "\u2190 " }),
          /* @__PURE__ */ jsx(Text, { color: isSelected ? "white" : "gray", children: label })
        ] });
      }
      if (item.type === "scope") {
        return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
          /* @__PURE__ */ jsxs(Box, { children: [
            /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
            /* @__PURE__ */ jsxs(Text, { children: [
              item.icon,
              " "
            ] }),
            /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: item.label })
          ] }),
          isSelected && /* @__PURE__ */ jsx(Box, { marginLeft: 4, children: /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: item.description }) })
        ] });
      }
      if (item.type === "add-new") {
        return /* @__PURE__ */ jsxs(Box, { children: [
          /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
          /* @__PURE__ */ jsx(Text, { color: isSelected ? "green" : "gray", children: "+ " }),
          /* @__PURE__ */ jsx(Text, { color: isSelected ? "green" : "gray", children: "Add custom marketplace" })
        ] });
      }
      if (item.type === "default-marketplace") {
        const icon = getSourceIcon(item.sourceType);
        return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
          /* @__PURE__ */ jsxs(Box, { children: [
            /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
            /* @__PURE__ */ jsxs(Text, { children: [
              icon,
              " "
            ] }),
            /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: item.name }),
            /* @__PURE__ */ jsx(Text, { color: "yellow", children: " (not installed)" })
          ] }),
          isSelected && /* @__PURE__ */ jsx(Box, { marginLeft: 4, children: /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: item.sourceValue }) })
        ] });
      }
      if (item.type === "marketplace") {
        const m = item.marketplace;
        const icon = getSourceIcon(m.source.type);
        return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
          /* @__PURE__ */ jsxs(Box, { children: [
            /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
            /* @__PURE__ */ jsxs(Text, { children: [
              icon,
              " "
            ] }),
            /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: m.name }),
            /* @__PURE__ */ jsxs(Text, { color: "gray", dimColor: true, children: [
              " ",
              "(",
              item.pluginCount,
              " plugins)"
            ] })
          ] }),
          isSelected && /* @__PURE__ */ jsx(Box, { marginLeft: 4, children: /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: m.source.value }) })
        ] });
      }
      const p = item.plugin;
      const statusBadge = item.isInstalled ? /* @__PURE__ */ jsx(Text, { color: "green", children: " \u2713" }) : null;
      return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
        /* @__PURE__ */ jsxs(Box, { children: [
          /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
          /* @__PURE__ */ jsx(Text, { color: isSelected ? "white" : "gray", children: "\u{1F4E6} " }),
          /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: p.name }),
          p.version && /* @__PURE__ */ jsxs(Text, { color: "gray", dimColor: true, children: [
            "@",
            p.version
          ] }),
          p.category && /* @__PURE__ */ jsxs(Text, { color: "magenta", dimColor: true, children: [
            " ",
            "[",
            p.category,
            "]"
          ] }),
          statusBadge
        ] }),
        isSelected && p.description && /* @__PURE__ */ jsx(Box, { marginLeft: 4, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: p.description }) }),
        isSelected && item.isInstalled && /* @__PURE__ */ jsx(Box, { marginLeft: 4, children: /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: "Already installed" }) })
      ] });
    };
    const handleSelect = async (item) => {
      if (item.type === "back") {
        if (view === "scope-select") {
          goBackToPlugins();
        } else if (view === "plugins") {
          goBackToMarketplaces();
        } else {
          onClose();
        }
        return;
      }
      if (item.type === "add-new") {
        onAction({ type: "add-marketplace" });
        return;
      }
      if (item.type === "default-marketplace" && !isInstalling) {
        setIsInstalling(true);
        try {
          await addMarketplace(item.sourceValue, { name: item.name });
          onAction({ type: "marketplace-added", marketplaceName: item.name });
          loadMarketplaces();
        } catch (error) {
          logger.error(
            `Failed to add marketplace ${item.name}: ${error instanceof Error ? error.message : String(error)}`
          );
        } finally {
          setIsInstalling(false);
        }
        return;
      }
      if (item.type === "marketplace") {
        showMarketplacePlugins(item.marketplace.name);
        return;
      }
      if (item.type === "plugin" && !item.isInstalled) {
        showScopeSelection(item.plugin);
        return;
      }
      if (item.type === "scope" && pendingPlugin && !isInstalling) {
        setIsInstalling(true);
        try {
          const result = await installPluginFromMarketplace(
            `${pendingPlugin.name}@${pendingPlugin.marketplace}`,
            { scope: item.scope }
          );
          setInstalledPluginNames((prev) => {
            const next = new Set(prev);
            next.add(result.pluginName.toLowerCase());
            return next;
          });
          onAction({
            type: "plugin-installed",
            pluginName: result.pluginName,
            marketplace: result.marketplace
          });
          goBackToPlugins();
        } catch (error) {
          logger.error(
            `Failed to install ${pendingPlugin.name}: ${error instanceof Error ? error.message : String(error)}`
          );
        } finally {
          setIsInstalling(false);
        }
      }
    };
    const getTitle = () => {
      if (view === "scope-select" && pendingPlugin) {
        return `Install ${pendingPlugin.name} \u203A Choose Scope`;
      }
      if (view === "plugins" && selectedMarketplace) {
        return `${selectedMarketplace} \u203A Plugins`;
      }
      return "Marketplace";
    };
    const getEmptyMessage = () => {
      if (loadError) return loadError;
      if (view === "plugins") return "No plugins found in this marketplace";
      return "No marketplaces. Add one to browse plugins.";
    };
    return /* @__PURE__ */ jsx(
      BaseSelector,
      {
        ref: baseSelectorRef,
        items,
        isVisible,
        isLoading: isLoading || isInstalling,
        selectedIndex,
        onSelectIndex: setSelectedIndex,
        onSelect: handleSelect,
        onClose,
        formatItem,
        title: getTitle(),
        borderColor: "green",
        emptyMessage: getEmptyMessage(),
        loadingMessage: isInstalling ? "Installing..." : "Loading..."
      }
    );
  }
);
var MarketplaceBrowser_default = MarketplaceBrowser;
export {
  MarketplaceBrowser_default as default
};
