"use client";
import { useApp, Wrapper } from "@hygraph/app-sdk-react";
import { useSearchParams } from "next/navigation";
import { useState } from "react";
function Setup({ code }: { code: string }) {
const { context, updateInstallation } = useApp();
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const managementApiBaseUrl = context.project.mgmtApi
.split("/")
.slice(0, -1)
.join("/");
const handleConnectApp = async () => {
setError(null);
setIsSubmitting(true);
try {
if (!code) {
throw new Error(
"Missing setup code. Please restart the app installation.",
);
}
const response = await fetch(`/api/exchangeSetupCode`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
code,
environmentId: context.environment.id,
managementApiBaseUrl,
}),
});
if (!response.ok) {
let message = "Failed to connect your app. Please try again.";
try {
const errorData = await response.json();
if (errorData?.message) {
message = errorData.message;
}
} catch {
}
throw new Error(message);
}
await updateInstallation({ status: "COMPLETED", config: {} });
} catch (caughtError) {
setError(
caughtError instanceof Error
? caughtError.message
: "Something went wrong while connecting your app.",
);
} finally {
setIsSubmitting(false);
}
};
return (
<>
<button onClick={handleConnectApp} disabled={isSubmitting}>
{isSubmitting ? "Connecting..." : "Connect your app"}
</button>
{error ? <p role="alert">{error}</p> : null}
</>
);
}
function SetupContent({ code }: { code: string }) {
const { installation } = useApp();
if (!installation) {
return <div>Loading installation...</div>;
}
if (installation.status === "COMPLETED") {
return <div>Installation completed</div>;
}
return <Setup code={code} />;
}
export default function SetupPage() {
const searchParams = useSearchParams();
const code = searchParams.get("code") ?? "";
return (
<Wrapper>
<SetupContent code={code} />
</Wrapper>
);
}