import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, forwardRef, useImperativeHandle, useCallback } from "react";
import { Box, Text } from "ink";
import { getPrimaryApiKeyEnvVar, saveProviderApiKey } from "@dexto/agent-management";
import { applyLayeredEnvironmentLoading } from "../../host/index.js";
import {
  getProviderDisplayName,
  isValidApiKeyFormat,
  getProviderInstructions
} from "../../host/index.js";
const ApiKeyInput = forwardRef(function ApiKeyInput2({ isVisible, provider, onSaved, onClose }, ref) {
  const [apiKey, setApiKey] = useState("");
  const [error, setError] = useState(null);
  const [isSaving, setIsSaving] = useState(false);
  useEffect(() => {
    if (isVisible) {
      setApiKey("");
      setError(null);
      setIsSaving(false);
    }
  }, [isVisible, provider]);
  const handleSubmit = useCallback(async () => {
    const trimmedKey = apiKey.trim();
    if (!trimmedKey) {
      setError("API key is required");
      return;
    }
    if (!isValidApiKeyFormat(trimmedKey, provider)) {
      setError(`Invalid ${getProviderDisplayName(provider)} API key format`);
      return;
    }
    setError(null);
    setIsSaving(true);
    try {
      const meta = await saveProviderApiKey(provider, trimmedKey, process.cwd());
      await applyLayeredEnvironmentLoading();
      onSaved({ provider, envVar: meta.envVar });
    } catch (err) {
      setError(`Failed to save: ${err instanceof Error ? err.message : String(err)}`);
      setIsSaving(false);
    }
  }, [apiKey, provider, onSaved]);
  useImperativeHandle(
    ref,
    () => ({
      handleInput: (input, key) => {
        if (!isVisible || isSaving) return false;
        if (key.escape) {
          onClose();
          return true;
        }
        if (key.return) {
          void handleSubmit();
          return true;
        }
        if (key.backspace || key.delete) {
          setApiKey((prev) => prev.slice(0, -1));
          setError(null);
          return true;
        }
        if (input && !key.ctrl && !key.meta) {
          setApiKey((prev) => prev + input);
          setError(null);
          return true;
        }
        return false;
      }
    }),
    [isVisible, isSaving, onClose, handleSubmit]
  );
  if (!isVisible) return null;
  const providerName = getProviderDisplayName(provider);
  const envVar = getPrimaryApiKeyEnvVar(provider);
  const instructions = getProviderInstructions(provider);
  const maskedKey = apiKey.length > 8 ? `${apiKey.slice(0, 4)}${"*".repeat(Math.min(apiKey.length - 8, 20))}${apiKey.slice(-4)}` : "*".repeat(apiKey.length);
  return /* @__PURE__ */ jsxs(
    Box,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: "cyan",
      paddingX: 1,
      marginTop: 1,
      children: [
        /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsxs(Text, { bold: true, color: "cyan", children: [
          "API Key Required for ",
          providerName
        ] }) }),
        instructions && /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: instructions.content }) }),
        /* @__PURE__ */ jsxs(Box, { marginBottom: 1, children: [
          /* @__PURE__ */ jsx(Text, { color: "gray", children: "This key will be saved to " }),
          /* @__PURE__ */ jsx(Text, { color: "yellowBright", children: envVar }),
          /* @__PURE__ */ jsx(Text, { color: "gray", children: " in your .env file" })
        ] }),
        /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: /* @__PURE__ */ jsxs(Text, { bold: true, children: [
          "Enter your ",
          providerName,
          " API key:"
        ] }) }),
        /* @__PURE__ */ jsxs(Box, { marginTop: 1, children: [
          /* @__PURE__ */ jsx(Text, { color: "cyan", children: "> " }),
          /* @__PURE__ */ jsx(Text, { children: maskedKey }),
          !isSaving && /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
        ] }),
        isSaving && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "yellowBright", children: "Saving API key..." }) }),
        error && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "red", children: error }) }),
        /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Enter to save \u2022 Esc to cancel" }) })
      ]
    }
  );
});
var ApiKeyInput_default = ApiKeyInput;
export {
  ApiKeyInput_default as default
};
