import { jsx, jsxs } from "react/jsx-runtime";
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from "react";
import { Box, Text } from "ink";
import {
  loadAuth,
  performDeviceCodeLogin,
  persistDeviceApiKeyLoginResult
} from "../../host/index.js";
const LoginOverlay = forwardRef(function LoginOverlay2({ isVisible, onDone }, ref) {
  const [step, setStep] = useState("checking");
  const [existingUser, setExistingUser] = useState(null);
  const [authUrl, setAuthUrl] = useState(null);
  const [devicePrompt, setDevicePrompt] = useState(null);
  const [status, setStatus] = useState("Preparing login...");
  const [error, setError] = useState(null);
  const abortControllerRef = useRef(null);
  const isActiveRef = useRef(false);
  const safeSetStatus = useCallback((message) => {
    if (!isActiveRef.current) return;
    setStatus(message);
  }, []);
  const cancelInFlight = useCallback(() => {
    abortControllerRef.current?.abort(new Error("Authentication cancelled"));
    abortControllerRef.current = null;
  }, []);
  const runDeviceLogin = useCallback(
    async (abortController) => {
      setStep("starting");
      safeSetStatus("Starting device code login...");
      setAuthUrl(null);
      setDevicePrompt(null);
      return performDeviceCodeLogin({
        signal: abortController.signal,
        onPrompt: (prompt) => {
          if (!isActiveRef.current || abortController.signal.aborted) {
            return;
          }
          setDevicePrompt(prompt);
          setAuthUrl(prompt.verificationUrlComplete ?? prompt.verificationUrl);
          setStep("waiting");
          safeSetStatus("Open the URL below and approve login.");
        }
      });
    },
    [safeSetStatus]
  );
  const startLogin = useCallback(async () => {
    cancelInFlight();
    setError(null);
    setAuthUrl(null);
    setDevicePrompt(null);
    const abortController = new AbortController();
    abortControllerRef.current = abortController;
    try {
      const result = await runDeviceLogin(abortController);
      if (!result || !isActiveRef.current || abortController.signal.aborted) return;
      setStep("finalizing");
      safeSetStatus("Finalizing login...");
      const persisted = await persistDeviceApiKeyLoginResult(result);
      if (!isActiveRef.current || abortController.signal.aborted) return;
      onDone({
        outcome: "success",
        email: persisted.email,
        keyId: persisted.keyId,
        hasDextoApiKey: persisted.hasDextoApiKey
      });
    } catch (err) {
      if (abortController.signal.aborted) {
        return;
      }
      setStep("error");
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      safeSetStatus("Login failed");
    } finally {
      abortControllerRef.current = null;
    }
  }, [cancelInFlight, onDone, runDeviceLogin, safeSetStatus]);
  useEffect(() => {
    if (!isVisible) return;
    isActiveRef.current = true;
    setStep("checking");
    setExistingUser(null);
    setAuthUrl(null);
    setDevicePrompt(null);
    setStatus("Preparing login...");
    setError(null);
    void (async () => {
      try {
        const auth = await loadAuth();
        if (!isActiveRef.current) return;
        if (auth) {
          setExistingUser(auth.email || auth.userId || "user");
          setStep("already-authenticated");
          setStatus("You are already logged in");
          return;
        }
        await startLogin();
      } catch (err) {
        if (!isActiveRef.current) return;
        setStep("error");
        setStatus("Error checking authentication state");
        setError(err instanceof Error ? err.message : String(err));
      }
    })();
    return () => {
      isActiveRef.current = false;
      cancelInFlight();
    };
  }, [cancelInFlight, isVisible, startLogin]);
  useImperativeHandle(
    ref,
    () => ({
      handleInput: (_input, key) => {
        if (!isVisible) return false;
        if (key.escape) {
          cancelInFlight();
          onDone({ outcome: step === "already-authenticated" ? "closed" : "cancelled" });
          return true;
        }
        if (step === "already-authenticated" && key.return) {
          void startLogin();
          return true;
        }
        if (step === "error" && key.return) {
          void startLogin();
          return true;
        }
        return true;
      }
    }),
    [cancelInFlight, isVisible, onDone, startLogin, step]
  );
  if (!isVisible) return null;
  const hint = step === "already-authenticated" ? "Enter to login again \u2022 Esc to close" : step === "error" ? "Enter to retry \u2022 Esc to close" : "Esc to cancel";
  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: "Login to Dexto" }) }),
        existingUser && step === "already-authenticated" && /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsxs(Text, { color: "green", children: [
          "\u2705 Already logged in as: ",
          existingUser
        ] }) }),
        /* @__PURE__ */ jsxs(Box, { marginBottom: 1, children: [
          /* @__PURE__ */ jsx(Text, { color: "gray", children: "Status: " }),
          /* @__PURE__ */ jsx(Text, { children: status })
        ] }),
        devicePrompt && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ jsx(Text, { color: "gray", children: "Open this URL on any device:" }),
          /* @__PURE__ */ jsx(Text, { color: "yellowBright", children: devicePrompt.verificationUrlComplete ?? devicePrompt.verificationUrl }),
          /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
            "Code: ",
            devicePrompt.userCode
          ] })
        ] }),
        authUrl && !devicePrompt && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ jsx(Text, { color: "gray", children: "If your browser didn't open, use this URL:" }),
          /* @__PURE__ */ jsx(Text, { color: "yellowBright", children: authUrl })
        ] }),
        error && /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ jsxs(Text, { color: "red", children: [
          "Error: ",
          error
        ] }) }),
        /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: hint }) })
      ]
    }
  );
});
var LoginOverlay_default = LoginOverlay;
export {
  LoginOverlay_default as default
};
