import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "@emotion/react/jsx-runtime";
import React from "react";
import { Button, Center, Flex, FormControl, FormHelperText, FormLabel, Heading, HStack, Image, Input, Select, Spacer, Text, useToast, VStack, } from "@chakra-ui/react";
import { useRouter } from "next/router";
import qoreStorageClient from "../../hooks/qoreStorageClient";
import { useForm } from "react-hook-form";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import EditorContext from "@qorebase/app-runtime/src/EditorContext";
import useSave from "../../hooks/useSaveApp";
import { convertFileToPublicURL } from "../../utils/convertFileToPublicURL";
const GeneralSetting = () => {
    var _a;
    const router = useRouter();
    const toast = useToast();
    const entryPage = RuntimeContext.useSelectState((state) => { var _a; return (_a = state.config.initialPage) === null || _a === void 0 ? void 0 : _a.entryPage; });
    const loggedInPage = RuntimeContext.useSelectState((state) => { var _a; return (_a = state.config.initialPage) === null || _a === void 0 ? void 0 : _a.loggedInPage; });
    const pagesMap = RuntimeContext.useSelectState((state) => state.maps.page);
    const appData = RuntimeContext.useSelectState((state) => state);
    const pageGroups = React.useMemo(() => Object.values(pagesMap).map((page) => ({
        title: page.title,
        id: page.id,
    })), [pagesMap]);
    const insertRevision = qoreStorageClient.table("revisions").useInsertRow();
    const inputFileRef = React.useRef(null);
    const form = useForm({
        mode: "onSubmit",
        defaultValues: {
            name: "",
            description: "",
            image: "",
        },
    });
    const { data: app, revalidate } = qoreStorageClient
        .table("applications")
        .useGetRow(router.query.appID, { skip: !router.isReady });
    const { user } = qoreStorageClient.useCurrentUser();
    const { clean } = RuntimeContext.useDirty();
    const updateApplication = qoreStorageClient
        .table("applications")
        .useUpdateRow();
    const runtimeActions = RuntimeContext.useActions();
    const editorActions = EditorContext.useActions();
    const currentApp = qoreStorageClient.view("application-detail").useListRow({
        params: {
            appId: router.query.appID,
            projectId: router.query.projectID,
        },
    });
    const appIcon = React.useMemo(() => (currentApp === null || currentApp === void 0 ? void 0 : currentApp.data[0]) &&
        convertFileToPublicURL("applications", "icon", currentApp.data[0].id, currentApp.data[0].icon), [currentApp]);
    const [image, setImage] = React.useState({
        src: "",
        file: undefined,
    });
    React.useEffect(() => {
        setImage((val) => (Object.assign(Object.assign({}, val), { src: appIcon })));
    }, [appIcon]);
    React.useEffect(() => {
        if (!app)
            return;
        runtimeActions.setIcon(appIcon || "");
        form.reset({
            name: app.name,
            description: app.description,
        });
    }, [app]);
    const onSubmit = React.useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        if (!app)
            return;
        const values = form.getValues();
        yield updateApplication.updateRow(app.id, {
            name: values.name,
            description: values.description,
        });
        if (image.file) {
            yield qoreStorageClient.client
                .table("applications")
                .upload(router.query.appID, "icon", image.file);
        }
        useSave(app.id, appData, user, editorActions.setRevisionID, clean, insertRevision.insertRow);
        revalidate();
        currentApp.revalidate();
        toast({
            status: "success",
            title: "Success Updated",
            description: "Data has been updated successfully",
        });
    }), [
        app,
        appData,
        inputFileRef,
        form,
        image,
        revalidate,
        (_a = router.query) === null || _a === void 0 ? void 0 : _a.projectID,
        currentApp.revalidate,
        insertRevision,
        user === null || user === void 0 ? void 0 : user.id,
        clean,
    ]);
    const handleUploadButton = () => {
        var _a;
        (_a = inputFileRef.current) === null || _a === void 0 ? void 0 : _a.click();
    };
    return (_jsxs(VStack, Object.assign({ as: "form", gap: "4", alignItems: "normal", onSubmit: form.handleSubmit(onSubmit) }, { children: [_jsxs(Flex, Object.assign({ direction: "column", fontSize: "18px", gap: 2 }, { children: [_jsx(Heading, Object.assign({ fontSize: "md" }, { children: "Apps Information" })), _jsx(Text, Object.assign({ color: "#747474", fontSize: "reg" }, { children: "General information about your apps" }))] })), _jsxs(FormControl, Object.assign({ id: "name" }, { children: [_jsx(FormLabel, Object.assign({ fontSize: "reg" }, { children: "App Name" })), _jsx(Input, { ref: form.register({ required: true }), placeholder: "Application name", fontSize: "reg", name: "name" })] })), _jsxs(FormControl, Object.assign({ id: "description" }, { children: [_jsx(FormLabel, Object.assign({ fontSize: "reg" }, { children: "App Description" })), _jsx(Input, { ref: form.register({ required: true }), placeholder: "About your app", fontSize: "reg", name: "description" })] })), _jsx(FormControl, Object.assign({ id: "icon" }, { children: _jsxs(HStack, { children: [_jsxs(Flex, Object.assign({ direction: "column", alignItems: "normal" }, { children: [_jsx(FormLabel, Object.assign({ fontSize: "reg" }, { children: "App Logo" })), _jsx(Text, Object.assign({ color: "#A2A2A2", fontSize: "reg" }, { children: "Click on logo to replace with your uploaded logo" }))] })), _jsx(Spacer, {}), _jsx(Center, Object.assign({ mt: "15px", border: "1px dashed", rounded: "md", borderColor: "gray.300" }, { children: _jsxs(_Fragment, { children: [_jsx(Image, { alt: "App logo", src: image.src, fallbackSrc: "/assets/placeholder.svg", h: "100px", objectFit: "cover", cursor: "pointer", onClick: handleUploadButton, background: "gray.50", rounded: "md", _hover: {
                                            bg: "gray.100",
                                        } }), _jsx(Input, { hidden: true, accept: "image/*", ref: inputFileRef, onChange: (e) => {
                                            var _a, _b;
                                            const file = (_b = (_a = e.currentTarget) === null || _a === void 0 ? void 0 : _a.files) === null || _b === void 0 ? void 0 : _b.item(0);
                                            if (!file)
                                                return;
                                            const fileSrc = URL.createObjectURL(file);
                                            setImage({ file, src: fileSrc });
                                        }, type: "file" })] }) }))] }) })), _jsxs(Flex, Object.assign({ direction: "column", fontSize: "18px", gap: 2 }, { children: [_jsx(Heading, Object.assign({ fontSize: "md" }, { children: "Initial Pages" })), _jsx(Text, Object.assign({ color: "#747474", fontSize: "reg" }, { children: "Set which page user will see when user opened your app or when logged in" }))] })), _jsxs(HStack, Object.assign({ width: "100%", gap: 5 }, { children: [_jsxs(FormControl, Object.assign({ width: "50%" }, { children: [_jsx(FormLabel, Object.assign({ fontSize: "reg" }, { children: "Entry page" })), _jsx(Select, Object.assign({ fontSize: "reg", placeholder: "Select entry page", value: entryPage, size: "sm", onChange: (e) => {
                                    runtimeActions.setInitialPage(e.currentTarget.value);
                                } }, { children: pageGroups.map((page, index) => (_jsx("option", Object.assign({ value: page.id }, { children: page.title }), index))) })), _jsx(FormHelperText, Object.assign({ color: "#A2A2A2" }, { children: "This is the first page user will see either user is logged in or not." }))] })), _jsxs(FormControl, Object.assign({ width: "50%" }, { children: [_jsx(FormLabel, Object.assign({ fontSize: "reg" }, { children: "Logged in page" })), _jsx(Select, Object.assign({ fontSize: "reg", placeholder: "Select logged in page", value: loggedInPage, size: "sm", onChange: (e) => {
                                    runtimeActions.setLoggedInPage(e.currentTarget.value);
                                } }, { children: pageGroups.map((page, index) => (_jsx("option", Object.assign({ value: page.id }, { children: page.title }), index))) })), _jsx(FormHelperText, Object.assign({ color: "#A2A2A2" }, { children: "User will see this page after they successfully logged in." }))] }))] })), _jsx(FormControl, Object.assign({ textAlign: "right" }, { children: _jsx(Button, Object.assign({ minW: "200px", mt: "20", disabled: form.formState.isSubmitting, isLoading: form.formState.isSubmitting, size: "sm", type: "submit", colorScheme: "blue", loadingText: "Saving..." }, { children: form.formState.isSubmitting ? "Saving.." : "Save" })) }))] })));
};
export default GeneralSetting;
//# sourceMappingURL=GeneralSetting.js.map