import { __awaiter, __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import React from "react";
import { Box, CloseButton, Flex, IconButton, Input, Menu, MenuButton, MenuItem, MenuList, Text, } from "@chakra-ui/react";
import qoreStorageClient from "../hooks/qoreStorageClient";
import { useRouter } from "next/router";
import dayjs from "dayjs";
import { MoreHorizontal } from "@feedloop/icon";
import EditorContext from "@qorebase/app-runtime/src/EditorContext";
import Scrollbars from "rc-scrollbars";
const RevisionComponent = (props) => {
    const { revision, isLatest } = props;
    const router = useRouter();
    const appId = router.query.appID;
    const [name, setName] = React.useState(revision.name);
    const [editMode, setEditMode] = React.useState(false);
    const editorActions = EditorContext.useActions();
    const { user } = qoreStorageClient.useCurrentUser();
    const onRename = React.useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        var _a, _b;
        const data = yield qoreStorageClient.client
            .table("revisions")
            .updateRow(revision.id, { name });
        const newRevision = (_b = (_a = data === null || data === void 0 ? void 0 : data.results) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b[0];
        (newRevision === null || newRevision === void 0 ? void 0 : newRevision.id) && editorActions.setRevisionID(newRevision.id);
    }), [revision, name]);
    const onRestore = React.useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        var _c, _d;
        if (!(user === null || user === void 0 ? void 0 : user.id))
            return;
        const { id, updated_at, "revision-user": revisionUser } = revision, revision_ = __rest(revision, ["id", "updated_at", "revision-user"]);
        const data = yield qoreStorageClient.client.table("revisions").insertRow(Object.assign(Object.assign({}, revision_), { "revision-user": user.id }));
        const newRevision = (_d = (_c = data === null || data === void 0 ? void 0 : data.results) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d[0];
        (newRevision === null || newRevision === void 0 ? void 0 : newRevision.id) && editorActions.setRevisionID(newRevision.id);
    }), [revision, user]);
    const onDeploy = React.useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        yield qoreStorageClient.client
            .table("applications")
            .updateRow(appId, { "production-revision": revision.id });
        editorActions.setRevisionID(revision.id);
    }), [revision, appId]);
    return (_jsxs(Flex, Object.assign({ px: 2, my: 2 }, { children: [_jsxs(Box, Object.assign({ flex: 1 }, { children: [revision["production-revision_items"].length > 0 && (_jsx(Text, Object.assign({ fontWeight: 600, color: "green.400" }, { children: "Deployed" }))), editMode ? (_jsx("form", Object.assign({ onSubmit: () => {
                            onRename();
                            setEditMode(false);
                        } }, { children: _jsx(Input, { size: "sm", placeholder: "Revision name", value: name, onChange: (e) => setName(e.target.value) }) }))) : (revision.name && (_jsx(Text, Object.assign({ fontSize: "md", fontWeight: 600 }, { children: revision.name })))), _jsx(Text, Object.assign({ fontSize: "md" }, { children: dayjs(revision.created_at).format("MMMM D, YYYY - h:mm") })), revision["revision-user"].name && (_jsx(Text, Object.assign({ color: "gray.400" }, { children: revision["revision-user"].name })))] })), _jsxs(Menu, Object.assign({ isLazy: true }, { children: [_jsx(MenuButton, { as: IconButton, "aria-label": "Options", icon: _jsx(MoreHorizontal, {}), variant: "ghost" }), _jsxs(MenuList, { children: [_jsx(MenuItem, Object.assign({ onClick: () => setEditMode(true) }, { children: "Rename" })), !isLatest && (_jsx(MenuItem, Object.assign({ onClick: onRestore }, { children: "Restore this version" }))), _jsx(MenuItem, Object.assign({ onClick: onDeploy }, { children: "Deploy this version" }))] })] }))] })));
};
const VersionHistoryPanel = () => {
    const router = useRouter();
    const editorActions = EditorContext.useActions();
    const { data = [], revalidate } = qoreStorageClient
        .table("revisions")
        .useListRow({
        condition: {
            apprevision: { $eq: router.query.appID },
        },
        orderBy: {
            updated_at: "DESC",
        },
        populate: ["revision-user", "production-revision_items"],
        limit: 20,
    });
    const deployedVersion = React.useMemo(() => {
        return (data.find((version) => version["production-revision_items"].length > 0) ||
            null);
    }, [data]);
    const [currentVersion, ...otherVersions] = data;
    const revisionId = EditorContext.useSelectState((state) => state.revisionID);
    React.useEffect(() => void revalidate(), [revisionId]);
    return (_jsx(Box, Object.assign({ bg: "white", borderLeft: "1px solid", borderColor: "gray.300", h: "full", position: "relative" }, { children: _jsxs(Scrollbars, { children: [_jsxs(Flex, Object.assign({ justifyContent: "space-between", h: "10", borderBottom: "1px solid", borderColor: "gray.300", alignItems: "center", pl: "4", pr: "1", position: "sticky", top: 0, bg: "white" }, { children: [_jsx(Text, Object.assign({ fontSize: "xl" }, { children: "Version History" })), _jsx(CloseButton, { onClick: () => editorActions.setRightPanel({ type: "page" }) })] })), _jsxs(Box, Object.assign({ py: "2" }, { children: [_jsxs(Box, Object.assign({ px: 4, paddingTop: 1 }, { children: [_jsx(Text, Object.assign({ fontWeight: 600, color: "gray.500" }, { children: "Deployed Version" })), deployedVersion ? (_jsx(RevisionComponent, { revision: deployedVersion, isLatest: true })) : (_jsx(Text, Object.assign({ fontSize: "md", fontWeight: 600, px: 2, my: 2 }, { children: "There is no deployed version yet" })))] })), _jsxs(Box, Object.assign({ px: 4, paddingTop: 1 }, { children: [_jsx(Text, Object.assign({ fontWeight: 600, color: "gray.500" }, { children: "Current Version" })), currentVersion && (_jsx(RevisionComponent, { revision: currentVersion, isLatest: true }))] })), otherVersions.length ? (_jsxs(Box, Object.assign({ px: 4, paddingTop: 1 }, { children: [_jsx(Text, Object.assign({ fontWeight: 600, color: "gray.500" }, { children: "Other Versions" })), otherVersions.map((version, i) => (_jsx(RevisionComponent, { revision: version, isLatest: false }, i)))] }))) : null] }))] }) })));
};
export default VersionHistoryPanel;
//# sourceMappingURL=VersionHistoryPanel.js.map