import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import React, { useEffect, useState } from "react";
import { Center, Grid, GridItem, Progress, Text } from "@chakra-ui/react";
import { BrowserRouter } from "react-router-dom";
import Runtime from "@qorebase/app-runtime/src/Runtime";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import PageManagerPanel from "./PageManagerPanel";
import TitleBar from "./TitleBar";
import EditorContext from "@qorebase/app-runtime/src/EditorContext";
import { VariablesProvider } from "@qorebase/app-runtime/src/VariablesContext";
import PreviewUser from "./PreviewUser";
import VersionHistoryPanel from "./VersionHistoryPanel";
import { EditorToastNotificationContextProvider } from "@qorebase/app-runtime/src/EditorToastNotification";
import variablesFieldTypes from "./variablesFieldTypes";
import PropertiesPanel from "./PropertiesPanel";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import Editor from "./Editor";
import EditorHeader from "./EditorHeader";
import EditorProvider from "./EditorProvider";
import SettingPage from "./SettingPage";
import AppearancePanel from "./AppearancePanel";
import ImageUploaderModal from "./ImageUploader";
import { useRouter } from "next/router";
import NavbarPanel from "./NavbarPanel";
import NavbarContent from "./NavbarContent";
import { usePageParam } from "@qorebase/app-runtime/src/hooks/usePageParam";
import { RouteProvider } from "./RouteProvider";
const AppLoading = () => {
    const [progress, setProgress] = useState(0);
    useEffect(() => {
        const interval = setInterval(() => {
            setProgress((progress) => progress + 1);
        }, 10);
        return () => clearInterval(interval);
    }, []);
    return (_jsxs(Center, Object.assign({ position: "absolute", top: "0", right: "0", bottom: "0", left: "0", flexDirection: "column", gap: "2", bg: "blackAlpha.50" }, { children: [_jsx(Progress, { value: progress, size: "xs", rounded: "full", w: "64", shadow: "inner", colorScheme: "blackAlpha" }), _jsx(Text, Object.assign({ fontSize: "xs" }, { children: "Loading application..." }))] })));
};
const AppPreview = (props) => {
    return (_jsx(Editor, { children: props.ready ? (_jsx(EditorProvider, { children: _jsx(Runtime, {}) })) : (_jsx(AppLoading, {})) }));
};
export default function EditorPage() {
    const router = useRouter();
    const basename = React.useMemo(() => Object.entries(router.query).reduce((path, [key, val]) => path.replace(`[${key}]`, val), router.route.replace("[[...appRoutes]]", "")), [router.route, router.query]);
    const pageID = usePageParam();
    const components = RuntimeContext.useSelectState((state) => state.maps.component);
    const activeWindow = EditorContext.useSelectState((state) => state.activeWindow);
    const rightPanel = EditorContext.useSelectState((state) => state.rightPanel);
    const ready = EditorContext.useSelectState((state) => state.ready);
    const revisionID = EditorContext.useSelectState((state) => state.revisionID);
    const tables = RuntimeContext.useSelectState((state) => state.schema.tables);
    const { isDirty } = RuntimeContext.useDirty();
    const usersFieldsSuggestions = React.useMemo(() => {
        var _a;
        return (((_a = tables
            .find((table) => table.name === "users")) === null || _a === void 0 ? void 0 : _a.columns.filter((field) => variablesFieldTypes.has(field.type)).concat({
            type: "text",
            name: "id",
        }).map((field) => ({
            id: `user.${field.name}`,
            display: `user.${field.name}`,
        })).concat([
            { id: "current_location", display: "current_location" },
            { id: "rowId", display: "rowId" },
            { id: "modalRowId", display: "modalRowId" },
        ])) || []);
    }, [tables]);
    const onUnload = React.useCallback((event) => {
        if (!isDirty) {
            return undefined;
        }
        event.preventDefault();
        return "Changes you've made might not be saved.";
    }, [isDirty]);
    React.useEffect(() => {
        window.addEventListener("beforeunload", onUnload);
        return () => window.removeEventListener("beforeunload", onUnload);
    }, [onUnload]);
    const showLeftRightPanel = React.useMemo(() => activeWindow === "preview", [activeWindow]);
    return (_jsx(BrowserRouter, Object.assign({ basename: basename }, { children: _jsx(PreviewUser, { children: _jsxs(VariablesProvider, Object.assign({ variables: usersFieldsSuggestions }, { children: [_jsx(EditorToastNotificationContextProvider, { children: _jsx(ImageUploaderModal, { children: _jsx(DndProvider, Object.assign({ backend: HTML5Backend }, { children: _jsxs(Grid, Object.assign({ templateAreas: `"header header ${showLeftRightPanel ? "header" : ""}"
                  "leftPanel main ${showLeftRightPanel ? "rightPanel" : ""}"`, gridTemplateRows: "50px 1fr", gridTemplateColumns: `${showLeftRightPanel ? "240px" : "0"} 1fr ${showLeftRightPanel ? "300px" : ""}`, h: "100vh", bg: "#e7e7e7" }, { children: [_jsxs(RouteProvider, { children: [_jsx(GridItem, Object.assign({ area: "header" }, { children: _jsx(EditorHeader, {}) })), showLeftRightPanel && (_jsx(GridItem, Object.assign({ area: "leftPanel", overflow: "hidden" }, { children: _jsx(PageManagerPanel, {}) })))] }), _jsx(GridItem, Object.assign({ area: "main", position: "relative", overflow: "hidden" }, { children: {
                                                settings: _jsx(SettingPage, {}),
                                                preview: _jsx(AppPreview, { ready: ready && !!components }),
                                            }[activeWindow] })), showLeftRightPanel && (_jsx(RouteProvider, { children: _jsx(GridItem, Object.assign({ area: "rightPanel", overflow: "hidden" }, { children: (() => {
                                                    switch (rightPanel.type) {
                                                        case "appearance":
                                                            return _jsx(AppearancePanel, {});
                                                        case "version history":
                                                            return _jsx(VersionHistoryPanel, {});
                                                        case "navbar":
                                                            return _jsx(NavbarPanel, {});
                                                        case "navbar content":
                                                            return _jsx(NavbarContent, {});
                                                        case "page":
                                                        case "component":
                                                            return _jsx(PropertiesPanel, {}, pageID);
                                                    }
                                                })() })) }))] })) })) }) }), _jsx(TitleBar, {}, revisionID)] })) }) })));
}
//# sourceMappingURL=EditorPage.js.map