import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import React, {
  useCallback,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState
} from "react";
import { Box, Text } from "ink";
import { getModelDisplayName, getReasoningProfile } from "@dexto/llm";
import { getLLMProviderDisplayName } from "../../utils/llm-provider-display.js";
const ReasoningOverlay = React.forwardRef(
  function ReasoningOverlay2({
    isVisible,
    agent,
    sessionId,
    showReasoning,
    onToggleShowReasoning,
    onSetBudgetTokens,
    onClose,
    onNotify
  }, ref) {
    const [selectedIndex, setSelectedIndex] = useState(0);
    const [mode, setMode] = useState("menu");
    const [budgetInput, setBudgetInput] = useState("");
    const [error, setError] = useState(null);
    const isSavingRef = useRef(false);
    const llmConfig = agent.getCurrentLLMConfig(sessionId || void 0);
    const provider = llmConfig.provider;
    const model = llmConfig.model;
    const support = getReasoningProfile(provider, model);
    const currentVariant = llmConfig.reasoning?.variant ?? support.defaultVariant ?? "default";
    const currentBudgetTokens = llmConfig.reasoning?.budgetTokens;
    const menuItems = useMemo(() => {
      const items = [
        {
          id: "toggle-visibility",
          label: showReasoning ? "Hide reasoning in chat" : "Show reasoning in chat",
          description: showReasoning ? "Keep tuning; hide reasoning blocks in the transcript" : "Show reasoning blocks in the transcript"
        }
      ];
      if (support.supportsBudgetTokens) {
        items.push({
          id: "set-budget",
          label: "Set reasoning budget tokens",
          description: "Advanced: cap/target reasoning budget (provider-specific)"
        });
        if (typeof currentBudgetTokens === "number") {
          items.push({
            id: "clear-budget",
            label: "Clear reasoning budget tokens",
            description: `Currently ${currentBudgetTokens}; revert to provider default`
          });
        }
      }
      return items;
    }, [showReasoning, support.supportsBudgetTokens, currentBudgetTokens]);
    useEffect(() => {
      if (!isVisible) return;
      setSelectedIndex(0);
      setMode("menu");
      setBudgetInput("");
      setError(null);
      isSavingRef.current = false;
    }, [isVisible]);
    useEffect(() => {
      if (!isVisible) return;
      setSelectedIndex((prev) => {
        if (menuItems.length === 0) return 0;
        return Math.min(prev, menuItems.length - 1);
      });
    }, [isVisible, menuItems.length]);
    const handleMenuSelect = useCallback(
      (item) => {
        setError(null);
        if (item.id === "toggle-visibility") {
          onToggleShowReasoning();
          onNotify(showReasoning ? "Reasoning hidden" : "Reasoning shown");
          return;
        }
        if (item.id === "set-budget") {
          setMode("budget-input");
          setBudgetInput(
            typeof currentBudgetTokens === "number" ? String(currentBudgetTokens) : ""
          );
          return;
        }
        if (item.id === "clear-budget") {
          void (async () => {
            if (isSavingRef.current) return;
            isSavingRef.current = true;
            try {
              await onSetBudgetTokens(void 0);
              onNotify("Reasoning budget cleared");
            } catch (e) {
              setError(
                `Failed to clear budget: ${e instanceof Error ? e.message : String(e)}`
              );
            } finally {
              isSavingRef.current = false;
            }
          })();
        }
      },
      [currentBudgetTokens, onNotify, onSetBudgetTokens, onToggleShowReasoning, showReasoning]
    );
    useImperativeHandle(
      ref,
      () => ({
        handleInput: (input, key) => {
          if (!isVisible) return false;
          if (key.escape) {
            if (mode === "budget-input") {
              setMode("menu");
              setError(null);
              return true;
            }
            onClose();
            return true;
          }
          if (mode === "budget-input") {
            if (isSavingRef.current) return true;
            if (key.return) {
              const trimmed = budgetInput.trim();
              const parsed = Number.parseInt(trimmed, 10);
              if (!trimmed) {
                setError("Enter a positive integer (or Esc to cancel)");
                return true;
              }
              if (!Number.isFinite(parsed) || parsed <= 0) {
                setError("Budget tokens must be a positive integer");
                return true;
              }
              void (async () => {
                if (isSavingRef.current) return;
                isSavingRef.current = true;
                try {
                  await onSetBudgetTokens(parsed);
                  onNotify(`Reasoning budget set to ${parsed}`);
                  setMode("menu");
                  setError(null);
                } catch (e) {
                  setError(
                    `Failed to set budget: ${e instanceof Error ? e.message : String(e)}`
                  );
                } finally {
                  isSavingRef.current = false;
                }
              })();
              return true;
            }
            if (key.backspace || key.delete) {
              setBudgetInput((prev) => prev.slice(0, -1));
              setError(null);
              return true;
            }
            if (input && !key.ctrl && !key.meta) {
              if (/^\d+$/.test(input)) {
                setBudgetInput((prev) => prev + input);
                setError(null);
                return true;
              }
            }
            return true;
          }
          if (menuItems.length > 0) {
            if (key.upArrow) {
              setSelectedIndex(
                (prev) => (prev - 1 + menuItems.length) % menuItems.length
              );
              return true;
            }
            if (key.downArrow) {
              setSelectedIndex((prev) => (prev + 1) % menuItems.length);
              return true;
            }
            if (key.return) {
              const item = menuItems[selectedIndex];
              if (item) {
                handleMenuSelect(item);
                return true;
              }
            }
          }
          return false;
        }
      }),
      [budgetInput, handleMenuSelect, isVisible, menuItems, mode, onClose, selectedIndex]
    );
    if (!isVisible) return null;
    const providerLabel = getLLMProviderDisplayName(provider, llmConfig.baseURL);
    const modelLabel = getModelDisplayName(model);
    return /* @__PURE__ */ jsxs(
      Box,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: "cyan",
        paddingX: 1,
        marginTop: 1,
        children: [
          /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { bold: true, color: "cyan", children: "Reasoning" }) }),
          /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
            /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
              "Model: ",
              /* @__PURE__ */ jsx(Text, { color: "white", children: modelLabel }),
              " ",
              /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
                "(",
                providerLabel,
                ")"
              ] })
            ] }),
            /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
              "Variant: ",
              /* @__PURE__ */ jsx(Text, { color: "white", children: currentVariant }),
              " ",
              /* @__PURE__ */ jsx(Text, { color: "gray", children: "(Tab cycles)" })
            ] }),
            /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
              "Visible: ",
              /* @__PURE__ */ jsx(Text, { color: "white", children: showReasoning ? "on" : "off" })
            ] }),
            /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
              "Budget tokens:",
              " ",
              /* @__PURE__ */ jsx(Text, { color: "white", children: support.supportsBudgetTokens ? typeof currentBudgetTokens === "number" ? String(currentBudgetTokens) : "none" : "not supported" })
            ] }),
            /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
              "Supported variants:",
              " ",
              /* @__PURE__ */ jsx(Text, { color: "white", children: support.supportedVariants.join(", ") })
            ] })
          ] }),
          mode === "budget-input" ? /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
            /* @__PURE__ */ jsx(Text, { bold: true, children: "Enter budget tokens:" }),
            /* @__PURE__ */ jsxs(Box, { marginTop: 1, children: [
              /* @__PURE__ */ jsx(Text, { color: "cyan", children: "> " }),
              /* @__PURE__ */ jsx(Text, { children: budgetInput }),
              !isSavingRef.current && /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
            ] }),
            /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Enter to save \u2022 Esc to cancel" }) })
          ] }) : /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: menuItems.length === 0 ? /* @__PURE__ */ jsx(Text, { color: "gray", children: "No reasoning options available for this model." }) : /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsxs(Text, { color: "cyan", bold: true, children: [
              "Options (",
              selectedIndex + 1,
              "/",
              menuItems.length,
              ") - \u2191\u2193 navigate, Enter select, Esc close"
            ] }),
            menuItems.map((item, idx) => {
              const isSelected = idx === selectedIndex;
              return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", marginTop: 0, children: [
                /* @__PURE__ */ jsx(Box, { width: 2, children: /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? ">" : " " }) }),
                /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
                  /* @__PURE__ */ jsx(
                    Text,
                    {
                      color: isSelected ? "cyan" : "gray",
                      bold: isSelected,
                      children: item.label
                    }
                  ),
                  /* @__PURE__ */ jsx(Text, { color: "gray", children: item.description })
                ] })
              ] }, item.id);
            })
          ] }) }),
          error && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "red", children: error }) })
        ]
      }
    );
  }
);
export {
  ReasoningOverlay
};
