import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import React from "react";
import { Box, Button, FormControl, FormHelperText, FormLabel, Input, InputGroup, InputRightAddon, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, Spinner, Text, Tooltip, VStack, } from "@chakra-ui/react";
import { useForm } from "react-hook-form";
import qoreStorageClient from "../hooks/qoreStorageClient";
import { useRouter } from "next/router";
import { initialApp, initialPage } from "@qorebase/app-runtime/src/InitialData";
import { subdomain } from "../../pages/apps/project/[projectID]/apps/[appID]/[[...appRoutes]]";
import useUpdateWhitelist from "../hooks/useUpdateWhitelist";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { CheckIcon, WarningIcon } from "@chakra-ui/icons";
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
const formSchema = yup.object().shape({
    name: yup.string().required().max(30),
    description: yup.string().required(),
    subdomain: yup.string().required().max(24),
});
export default function CreateApplicationModal({ disclosure, }) {
    var _a;
    const form = useForm({
        defaultValues: {
            name: "Untitled app",
            description: "",
            subdomain: subdomain(),
        },
        resolver: yupResolver(formSchema),
    });
    const router = useRouter();
    const [isSubmitting, setIsSubmitting] = React.useState(false);
    const { data: domains, error: domainsError, status, } = qoreStorageClient.table("domains").useListRow({
        condition: { address: { $eq: form.getValues().subdomain } },
    });
    const { data: environment } = qoreStorageClient
        .table("environment")
        .useListRow({
        condition: {
            project: router.query.projectID,
            name: "staging",
        },
    });
    const createApp = qoreStorageClient.table("applications").useInsertRow();
    const createRevision = qoreStorageClient.table("revisions").useInsertRow();
    const createDomain = qoreStorageClient.table("domains").useInsertRow();
    const regex = /^((?!-))(xn--)?[a-z0-9][a-z0-9-]{0,24}$/g;
    const { user } = qoreStorageClient.useCurrentUser();
    const isInputted = React.useMemo(() => {
        var _a;
        const formValues = form.watch();
        if (((_a = formValues.name) === null || _a === void 0 ? void 0 : _a.length) > 0 &&
            formValues.description.length > 0 &&
            formValues.subdomain.length > 0) {
            return false;
        }
        else {
            return true;
        }
    }, [form]);
    const whitelistNewDomain = useUpdateWhitelist(router.query.projectID);
    const isValidDomain = React.useMemo(() => {
        const subdomainValues = form.watch().subdomain;
        if (subdomainValues.length > 0) {
            if (subdomainValues.indexOf(" ") >= 0 ||
                domains.length > 0 ||
                regex.test(subdomainValues) === false) {
                return domains.length > 0
                    ? { valid: false, message: "The domain is taken. Try another" }
                    : {
                        valid: false,
                        message: "The domain format is wrong. The name should not containing any spaces or special characters",
                    };
            }
            else {
                return { valid: true, message: "Domain available" };
            }
        }
        else {
            return { valid: false, message: "The domain is required" };
        }
    }, [isInputted, form]);
    return (_jsxs(Modal, Object.assign({ isOpen: disclosure.isOpen, onClose: disclosure.onClose }, { children: [_jsx(ModalOverlay, {}), _jsxs(ModalContent, Object.assign({ as: "form", onSubmit: form.handleSubmit((values) => __awaiter(this, void 0, void 0, function* () {
                    var _b, _c, _d;
                    if (!(user === null || user === void 0 ? void 0 : user.id))
                        return;
                    setIsSubmitting(true);
                    try {
                        if (!!domainsError || !isValidDomain.valid) {
                            throw new Error("Invalid domains");
                        }
                        const environmentId = (_b = environment === null || environment === void 0 ? void 0 : environment[0]) === null || _b === void 0 ? void 0 : _b.id;
                        const app = yield createApp.insertRow({
                            name: values.name,
                            description: values.description,
                            project: router.query.projectID,
                            app_environment: environmentId,
                        });
                        const appId = (_d = (_c = app.results.data) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.id;
                        initialApp.maps.page.Home = Object.assign(Object.assign({}, initialPage), { type: "navigation" });
                        // eslint-disable-next-line @typescript-eslint/no-unused-vars
                        const revision = yield createRevision.insertRow({
                            name: "Revision",
                            // @ts-ignore
                            data: initialApp,
                            apprevision: appId,
                            "revision-user": user.id,
                        });
                        yield createDomain.insertRow({
                            appdomain: appId,
                            address: values.subdomain,
                            type: "Hosted",
                        });
                        yield whitelistNewDomain(values.subdomain);
                        disclosure.onClose();
                        router.push("/apps/project/[projectID]/apps/[appID]", `/apps/project/${router.query.projectID}/apps/${appId}`);
                        setIsSubmitting(false);
                    }
                    catch (err) {
                        setIsSubmitting(false);
                    }
                })) }, { children: [_jsx(ModalHeader, Object.assign({ fontSize: "lg" }, { children: "Create a new application" })), _jsx(ModalCloseButton, {}), _jsx(ModalBody, { children: _jsx(Box, Object.assign({ width: "full" }, { children: _jsxs(VStack, Object.assign({ spacing: 4 }, { children: [_jsxs(FormControl, Object.assign({ id: "name" }, { children: [_jsx(FormLabel, { children: "Application name" }), _jsx(Input, { name: "name", ref: form.register({ required: true }), placeholder: "Your application name", isInvalid: !!form.errors.name, errorBorderColor: form.errors.name && "red.500", fontSize: "sm" }), _jsx(FormHelperText, Object.assign({ color: "red.500" }, { children: (_a = form.errors.name) === null || _a === void 0 ? void 0 : _a.message }))] })), _jsxs(FormControl, Object.assign({ id: "description" }, { children: [_jsx(FormLabel, { children: "Description" }), _jsx(Input, { name: "description", ref: form.register({ required: true }), placeholder: "About your app", fontSize: "sm" })] })), _jsxs(FormControl, Object.assign({ id: "subdomain" }, { children: [_jsx(FormLabel, { children: "Subdomain" }), _jsxs(InputGroup, { children: [_jsx(Input, { name: "subdomain", ref: form.register({
                                                            required: true,
                                                        }), placeholder: "Your application subdomain", isInvalid: !!form.errors.subdomain || !isValidDomain.valid, errorBorderColor: (!isValidDomain.valid || form.errors.subdomain) &&
                                                            "red.500", fontSize: "sm" }), _jsx(InputRightAddon, { children: _jsxs(Box, Object.assign({ display: "flex", alignItems: "center" }, { children: [_jsx(Text, Object.assign({ marginRight: "16px", fontSize: "sm" }, { children: publicRuntimeConfig.appsDomain })), status === "loading" ? (_jsx(Tooltip, Object.assign({ hasArrow: true, label: "Checking", fontSize: "md" }, { children: _jsx(Spinner, { size: "sm", color: "blue.500" }) }))) : isValidDomain.valid && !form.errors.subdomain ? (_jsx(Tooltip, Object.assign({ hasArrow: true, label: isValidDomain.message, fontSize: "sm" }, { children: _jsx(CheckIcon, { color: "green.500" }) }))) : (_jsx(Tooltip, Object.assign({ hasArrow: true, label: isValidDomain.message, fontSize: "sm" }, { children: _jsx(WarningIcon, { color: "red.500" }) })))] })) })] }), !!form.errors.subdomain && (_jsx(FormHelperText, Object.assign({ color: "red.500" }, { children: form.errors.subdomain.message })))] }))] })) })) }), _jsxs(ModalFooter, { children: [_jsx(Button, Object.assign({ mr: 3, onClick: disclosure.onClose, size: "sm" }, { children: "Cancel" })), _jsx(Button, Object.assign({ size: "sm", colorScheme: "brand", type: "submit", disabled: isInputted ||
                                    isSubmitting ||
                                    !isValidDomain.valid ||
                                    status === "loading", "data-test": "create-app-button" }, { children: isSubmitting ? "Creating..." : "Create" }))] })] }))] })));
}
//# sourceMappingURL=CreateApplicationModal.js.map