import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { css, CacheProvider } from "@emotion/react";
import React from "react";
import useAspectRatioDimension from "../../hooks/useAspectRatioDimension";
import iconsList from "@qorebase/app-runtime/src/components/iconsList";
import createCache from "@emotion/cache";
import weakMemoize from "@emotion/weak-memoize";
import { FrameContextConsumer } from "react-frame-component";
import { Box, Button, ButtonGroup, Center, Flex, Icon, IconButton, Image, Modal, ModalBody, ModalContent, ModalOverlay, Text, Tooltip, useDisclosure, } from "@chakra-ui/react";
import { Play, RotateRight } from "@feedloop/icon";
import LoginAsUser from "../LoginAsUser";
import EditorContext from "@qorebase/app-runtime/src/EditorContext";
import SaveButton from "../SaveButton";
import qoreStorageClient from "../../hooks/qoreStorageClient";
import { useRouter } from "next/router";
import { importCustomComponent } from "@qorebase/app-runtime/src/utils/importComponent";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import EditorToastNotification from "@qorebase/app-runtime/src/EditorToastNotification";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import DevicePreviewsMap from "./DevicePreviewsMap";
import { usePageParam } from "@qorebase/app-runtime/src/hooks/usePageParam";
export var DevicePreviewType;
(function (DevicePreviewType) {
    DevicePreviewType["EDITOR"] = "Editor";
    DevicePreviewType["PREVIEW"] = "Preview";
})(DevicePreviewType || (DevicePreviewType = {}));
const memoizedCreateCacheWithContainer = weakMemoize((container) => {
    // @ts-ignore
    const newCache = createCache({ key: "runtime", container });
    return newCache;
});
export const FrameProvider = ({ children, }) => (_jsx(FrameContextConsumer, { children: ({ document, window }) => {
        return (_jsx(CacheProvider, Object.assign({ value: memoizedCreateCacheWithContainer(document.head) }, { children: _jsx(DndProvider, Object.assign({ backend: HTML5Backend, context: window }, { children: children })) })));
    } }));
const ModalLayout = (props) => (_jsxs(Modal, Object.assign({ isOpen: props.isOpen, onClose: props.onClose, isCentered: true }, { children: [_jsx(ModalOverlay, {}), _jsx(ModalContent, Object.assign({ w: "552px" }, { children: _jsxs(ModalBody, Object.assign({ py: "25px" }, { children: [_jsx(Center, { children: _jsx(Image, { src: "/assets/colom.svg", alt: "Desktop" }) }), _jsx(Center, Object.assign({ pt: 2 }, { children: _jsx(Text, Object.assign({ css: css `
              font-weight: 600;
              font-size: 24px;
              color: #001e4d;
            ` }, { children: "Use Layout Component" })) })), _jsx(Center, Object.assign({ pt: 2 }, { children: _jsx(Text, Object.assign({ css: css `
              font-weight: normal;
              font-size: 12px;
              color: #6f809a;
              text-align: center;
            ` }, { children: "You can add layout component on dekstop mode for get better visual & experience, layout component just for make group for component" })) })), _jsx(Center, Object.assign({ pt: 4 }, { children: _jsx(Button, Object.assign({ w: "100%", css: css `
              background: #0065ff;
              color: #fff;
            `, onClick: () => {
                                localStorage.setItem("layoutInformation", "open");
                                props.onClose();
                            } }, { children: "OK" })) }))] })) }))] })));
const DeviceSelectItem = ({ device, preview, deviceIcon, modalInfo, setState, onOpen }) => {
    const handleClick = React.useCallback(() => {
        const preview = device;
        setState({ preview });
        if (preview === "Desktop" && !modalInfo) {
            onOpen();
        }
    }, [device]);
    return (_jsx(IconButton, { "aria-label": device, borderRadius: "md", onClick: handleClick, icon: _jsx(Icon, { boxSize: "20px", as: iconsList[deviceIcon], color: preview === device ? "white" : "gray.600" }), colorScheme: preview === device ? "blue" : "white" }));
};
function DevicePreview(props) {
    const router = useRouter();
    const ready = EditorContext.useSelectState((state) => state.ready);
    const appDomains = qoreStorageClient.table("domains").useListRow({
        condition: {
            $and: [
                {
                    appdomain: {
                        $eq: router.query.appID,
                    },
                },
            ],
        },
        limit: 1,
    }, { skip: !router.isReady });
    const defaultDomain = appDomains.data[0];
    const devices = React.useMemo(() => Object.keys(DevicePreviewsMap()), []);
    const [state, setState] = React.useState({
        preview: devices[0],
    });
    const Preview = React.useMemo(() => DevicePreviewsMap()[state.preview], [state.preview]);
    const layoutModal = localStorage.getItem("layoutInformation");
    const deviceIcon = ["IconMobilePhone", "IconTablet", "IconDesktop"];
    const aspectRatio = useAspectRatioDimension(Preview.width, Preview.height);
    const { isOpen, onOpen, onClose } = useDisclosure();
    const ModalItem = ModalLayout;
    const editMode = EditorContext.useSelectState((state) => state.editMode);
    const editorActions = EditorContext.useActions();
    const rightPanel = EditorContext.useSelectState((state) => state.rightPanel);
    const page = usePageParam();
    const components = RuntimeContext.useSelectState((state) => state.maps.component);
    const localComponents = React.useMemo(() => (Object.values(components) || []).reduce((urls, component) => {
        var _a;
        return ((_a = component.metadata.componentURL) === null || _a === void 0 ? void 0 : _a.startsWith("http://localhost"))
            ? urls.concat(component.metadata.componentURL)
            : urls;
    }, []), [components]);
    const reloadLocalComponents = React.useCallback(() => __awaiter(this, void 0, void 0, function* () {
        yield Promise.all(localComponents.map((componentUrl) => importCustomComponent(componentUrl)));
    }), [localComponents, page]);
    const handleChangeToPlayMode = React.useCallback(() => {
        editorActions.setEditMode("play");
    }, []);
    const handleChangeToSelectMode = React.useCallback(() => {
        editorActions.setEditMode("select");
    }, []);
    return (_jsxs(Box, Object.assign({ css: css `
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
      `, bgColor: "#e7e7e7" }, { children: [_jsx(Box, Object.assign({ css: css `
          position: absolute;
          top: 0;
          bottom: 0;
          right: 0;
          left: 0;
          margin: 10px;
        ` }, { children: _jsx(Box, Object.assign({ ref: aspectRatio.containerRef, css: css `
            position: relative;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
          ` }, { children: _jsx(Box, Object.assign({ transform: `scale(${aspectRatio.scale * 1})` }, { children: _jsx(Preview.Component, { children: props.children }) })) })) })), _jsx(Box, Object.assign({ css: css `
          position: absolute;
          top: 0;
          right: 0;
          left: 0;
          padding: 8px;
          background-color: transparent;
        ` }, { children: _jsxs(Flex, Object.assign({ justifyContent: "space-between" }, { children: [_jsx(ButtonGroup, Object.assign({ variant: "solid", spacing: "2", p: 1, border: "1px", borderColor: "gray.300", borderRadius: "md", size: "sm" }, { children: devices.map((device, index) => (_jsx(DeviceSelectItem, { device: device, preview: state.preview, deviceIcon: deviceIcon[index], setState: setState, onOpen: onOpen, modalInfo: layoutModal }, `${device}-${index}`))) })), _jsxs(Flex, { children: [localComponents.length > 0 && (_jsx(IconButton, { "aria-label": "Version History", size: "sm", rounded: "sm", icon: _jsx(RotateRight, {}), colorScheme: "brand", variant: "outline", onClick: reloadLocalComponents, marginRight: 3 })), _jsx(IconButton, { "aria-label": "Version History", size: "sm", rounded: "sm", icon: _jsx(RotateRight, {}), colorScheme: "brand", variant: "outline", onClick: () => editorActions.setRightPanel({
                                        type: rightPanel.type === "version history"
                                            ? "page"
                                            : "version history",
                                    }), marginRight: 3 }), ready && _jsx(SaveButton, {}), _jsx(Tooltip, Object.assign({ hasArrow: true, label: "Add a domain in the App settings to run preview", rounded: "sm", placement: "bottom-start" }, { children: _jsx(IconButton, { "aria-label": "Preview", size: "sm", rounded: "sm", onClick: defaultDomain
                                            ? () => {
                                                window.open(`${window.location.origin}/app/preview/apps/${router.query.appID}/domains/${(defaultDomain === null || defaultDomain === void 0 ? void 0 : defaultDomain.address) || ""}`, "_blank");
                                            }
                                            : undefined, icon: _jsx(Play, {}), colorScheme: "brand", variant: "solid", marginX: 3 }) })), props.displayLoginAsUser && ready && _jsx(LoginAsUser, {})] })] })) })), _jsx(Box, Object.assign({ position: "absolute", right: 0, bottom: 0, padding: "8px", backgroundColor: "transparent" }, { children: _jsxs(ButtonGroup, Object.assign({ variant: "solid", p: 1, border: "1px", borderColor: "gray.300", borderRadius: "md", size: "sm" }, { children: [_jsx(Tooltip, Object.assign({ label: "Select mode" }, { children: _jsx(IconButton, { "aria-label": "select-mode", borderRadius: "md", icon: _jsx(Icon, { boxSize: "20px", as: iconsList["IconPencil"], color: editMode === "select" ? "white" : "gray.600", name: "HELLO2" }), colorScheme: editMode === "select" ? "blue" : "white", onClick: handleChangeToSelectMode }) })), _jsx(Tooltip, Object.assign({ label: "Play mode" }, { children: _jsx(IconButton, { "aria-label": "play-mode", borderRadius: "md", icon: _jsx(Icon, { boxSize: "20px", as: iconsList["Play"], color: editMode === "play" ? "white" : "gray.600", name: "HELLO" }), colorScheme: editMode === "play" ? "blue" : "white", onClick: handleChangeToPlayMode }) }))] })) })), _jsx(Box, Object.assign({ position: "absolute", bottom: 0, left: "50%", transform: "translate(-50%)", padding: "8px", backgroundColor: "transparent" }, { children: _jsx(EditorToastNotification, {}) })), _jsx(ModalItem, { isOpen: isOpen, onClose: onClose })] })));
}
export default React.memo(DevicePreview);
//# sourceMappingURL=index.js.map