import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import AtlasIcon from "@powerhousedao/connect/assets/icons/Atlas-Logomark.svg?react";
import RefreshIcon from "@powerhousedao/connect/assets/icons/refresh.svg?react";
import { PowerhouseButton } from "@powerhousedao/design-system";
import { addRemoteDrive } from "@powerhousedao/reactor-browser";
import { useReactor } from "@powerhousedao/reactor-browser/connect";
import { gql, request } from "graphql-request";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { toast } from "../../services/toast.js";
const REACTOR_URL = "https://apps.powerhouse.io/sky-atlas/staging/switchboard";
const MIN_LOADING_TIME = 2000;
function useReactorUrl() {
    const { search } = useLocation();
    return useMemo(() => {
        const params = new URLSearchParams(search);
        const url = params.get("reactorUrl") ?? REACTOR_URL;
        return url.endsWith("/") ? url : `${url}/`;
    }, [search]);
}
async function forkAtlas(docId, reactorUrl) {
    const document = gql `
    mutation ForkAtlas($docId: PHID) {
      ForkAtlas(docId: $docId)
    }
  `;
    return await request(`${reactorUrl}graphql`, document, { docId });
}
export function AtlasImport() {
    const status = useRef("initial");
    const reactor = useReactor();
    const { documentId } = useParams();
    const reactorUrl = useReactorUrl();
    const navigate = useNavigate();
    const [driveId, setDriveId] = useState(undefined);
    const [error, setError] = useState(undefined);
    const [loading, setLoading] = useState(true);
    const hasError = status.current === "error";
    useEffect(() => {
        if (error) {
            console.error("Error forking Atlas:", error);
            toast("Error forking Atlas", { type: "error" });
        }
    }, [error]);
    async function forkAtlasDocument(documentId) {
        const result = await forkAtlas(documentId, reactorUrl);
        const driveId = result.ForkAtlas;
        status.current = "forked";
        setDriveId(driveId);
    }
    const redirectToDrive = useCallback(() => {
        if (driveId && !loading) {
            navigate(`/d/${driveId}`, { replace: true });
        }
    }, [driveId, navigate, loading]);
    const addForkDrive = useCallback(async (driveId) => {
        console.log("Adding remote drive:", driveId);
        const driveUrl = `${reactorUrl}d/${driveId}`;
        try {
            const addedDrive = await addRemoteDrive(driveUrl, {
                sharingType: "PUBLIC",
                availableOffline: true,
                listeners: [
                    {
                        block: true,
                        callInfo: {
                            data: driveUrl,
                            name: "switchboard-push",
                            transmitterType: "SwitchboardPush",
                        },
                        filter: {
                            branch: ["main"],
                            documentId: ["*"],
                            documentType: ["*"],
                            scope: ["global"],
                        },
                        label: "Switchboard Sync",
                        listenerId: "1",
                        system: true,
                    },
                ],
                triggers: [],
            });
            status.current = "done";
            console.log("Added remote drive:", addedDrive);
            setTimeout(() => {
                setLoading(false);
            }, MIN_LOADING_TIME);
        }
        catch (error) {
            status.current = "error";
            setLoading(false);
            setError(error);
        }
    }, [addRemoteDrive, navigate, reactorUrl]);
    useEffect(() => {
        if (!documentId || status.current !== "initial")
            return;
        status.current = "forking";
        forkAtlasDocument(documentId).catch((error) => {
            status.current = "error";
            setError(error);
        });
    }, [documentId, status]);
    useEffect(() => {
        if (!driveId || !reactor || status.current !== "forked")
            return;
        status.current = "addingDrive";
        new Promise((resolve) => {
            setTimeout(resolve, 500);
        })
            .then(() => addForkDrive(driveId))
            .catch((error) => {
            status.current = "error";
            setError(error);
        });
    }, [driveId, reactor, status]);
    return (_jsx("div", { className: "flex size-full justify-center gap-x-4 bg-gray-50", children: _jsxs("div", { className: "w-full max-w-[850px] rounded-2xl bg-white p-6 drop-shadow-sm", children: [_jsx("h1", { className: "text-lg font-medium text-gray-900", children: "Welcome to the Atlas Explorer" }), _jsx("div", { className: "mt-4 rounded-xl border border-gray-200 bg-gray-50 p-6", children: _jsxs("div", { className: "flex min-h-80 flex-col items-center justify-center rounded-2xl bg-slate-50", children: [_jsx("div", { children: _jsx(AtlasIcon, {}) }), hasError ? (_jsx("div", { className: "mt-3 text-sm text-gray-800", children: "Error forking Atlas scope. Please try again." })) : (_jsx("div", { className: "mt-3 text-sm text-gray-500", children: "Forking Atlas scope..." })), _jsx(PowerhouseButton, { onClick: hasError
                                    ? window.location.reload.bind(window.location)
                                    : redirectToDrive, size: "small", color: "light", className: "mt-4 h-9 border border-gray-200 bg-white px-3 text-gray-600", children: hasError ? ("Retry") : loading ? (_jsxs(_Fragment, { children: [_jsx(RefreshIcon, { className: "animate-spin" }), "Loading"] })) : ("Continue") })] }) })] }) }));
}
//# sourceMappingURL=atlas-import.js.map