import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { Box, Button, FormControl, FormLabel, Heading, Icon, Input, InputGroup, InputLeftElement, InputRightElement, Text, VStack, Alert, AlertIcon, AlertDescription, } from "@chakra-ui/react";
import { css } from "@emotion/react";
import { useForm } from "react-hook-form";
import { useNavigate, useLocation } from "react-router-dom";
import qore from "../hooks/qore";
import React from "react";
import { LockIcon, ViewIcon, ViewOffIcon, SmallCloseIcon, } from "@chakra-ui/icons";
import aixp from "../integrations/aixp";
import { RuntimeContext } from "../RuntimeContext";
import * as queryString from "../utils/query-string";
import { v4 as uuidv4 } from "uuid";
export default function UserLogin() {
    var _a, _b, _c;
    const form = useForm({
        mode: "onChange",
        defaultValues: { email: "", password: "" },
    });
    const navigate = useNavigate();
    const location = useLocation();
    const client = qore.useClient();
    const loggedInPage = RuntimeContext.useSelectState((state) => { var _a; return (_a = state.config.initialPage) === null || _a === void 0 ? void 0 : _a.loggedInPage; });
    const aixpIntegration = aixp.useIntegration();
    const [showPassword, setShowPassword] = React.useState(false);
    const config = RuntimeContext.useSelectState((state) => state.config);
    const { user } = qore.useCurrentUser();
    const { refetch: refetchUser } = qore.useCurrentUser();
    const onSubmit = React.useCallback((values) => __awaiter(this, void 0, void 0, function* () {
        var _d;
        try {
            const token = yield client.authenticate(values.email, values.password);
            localStorage.setItem(`${config.projectID}_user_token`, token);
            const { user } = yield refetchUser();
            aixpIntegration.run((integration) => {
                integration.identify({
                    userId: user.id,
                    anonymousId: uuidv4(),
                    traits: user,
                });
                integration.track({
                    userId: user.external_id,
                    anonymousId: uuidv4(),
                    event: "login",
                    properties: Object.assign(Object.assign({}, user), { role: user.role.name }),
                    context: {
                        traits: user,
                    },
                });
            });
        }
        catch (errors) {
            const response = errors.response;
            if (((_d = response === null || response === void 0 ? void 0 : response.data) === null || _d === void 0 ? void 0 : _d.error) === "Unauthorized") {
                form.setError("email", {
                    type: "api",
                    message: response.data.message,
                });
            }
        }
    }), [config.projectID, refetchUser]);
    React.useEffect(function redirectAfterLoginAsUser() {
        if (user && location.pathname === "/page/login") {
            const { redirectRoot } = queryString.parse(location.search);
            const { nextPage } = queryString.parse(location.search);
            const url = loggedInPage ? `/page/${loggedInPage}` : nextPage;
            url && !redirectRoot ? navigate(url) : navigate("/");
        }
    }, [
        user,
        location.pathname,
        history === null || history === void 0 ? void 0 : history.length,
        location.search,
        navigate,
        loggedInPage,
    ]);
    return (_jsxs(Box, Object.assign({ css: css `
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        flex-direction: column;
        padding: 16px;
      ` }, { children: [_jsxs(Box, Object.assign({ pb: 8 }, { children: [_jsx(Heading, Object.assign({ fontSize: "3xl" }, { children: "Login" })), _jsx(Text, Object.assign({ color: "gray.400" }, { children: "Login to continue your action." }))] })), _jsx(Box, Object.assign({ as: "form", onSubmit: form.handleSubmit(onSubmit), width: "full" }, { children: _jsxs(VStack, Object.assign({ spacing: 4 }, { children: [_jsxs(FormControl, Object.assign({ id: "email" }, { children: [_jsx(FormLabel, { children: "Email Address" }), _jsx(Input, { name: "email", ref: form.register({ required: true }), placeholder: "Your email here", size: "lg", "data-test": "input-email" })] })), _jsxs(FormControl, Object.assign({ id: "password" }, { children: [_jsx(FormLabel, { children: "Password" }), _jsxs(InputGroup, Object.assign({ size: "lg" }, { children: [_jsx(InputLeftElement, Object.assign({ pointerEvents: "none", color: "gray.300", fontSize: "1.2em" }, { children: _jsx(LockIcon, {}) })), _jsx(Input, { name: "password", type: showPassword ? "text" : "password", ref: form.register({ required: true }), placeholder: "Enter your password", "data-test": "input-password" }), _jsx(InputRightElement, { children: _jsx(Icon, { onClick: () => setShowPassword(!showPassword), as: showPassword ? ViewOffIcon : ViewIcon }) })] }))] })), _jsxs(VStack, Object.assign({ spacing: 6, pt: 6, width: "full" }, { children: [((_b = (_a = form.formState.errors) === null || _a === void 0 ? void 0 : _a.email) === null || _b === void 0 ? void 0 : _b.type) === "api" && (_jsxs(Alert, Object.assign({ bg: "red.50", color: "darkred" }, { children: [_jsx(AlertIcon, { as: SmallCloseIcon, alignSelf: "start", color: "red.50", rounded: "full", bgColor: "#901607", mt: "1", mr: "15px", h: 5 }), _jsx(AlertDescription, { children: (_c = form.formState.errors.email) === null || _c === void 0 ? void 0 : _c.message })] }))), _jsx(Button, Object.assign({ width: "full", size: "lg", type: "submit", isLoading: form.formState.isSubmitting, "data-test": "sign-in-button" }, { children: "Login" })), _jsx(Button, Object.assign({ onClick: () => navigate("/page/register"), width: "full", size: "lg", variant: "link", "data-test": "sign-up-button" }, { children: "Create Account" }))] }))] })) }))] })));
}
//# sourceMappingURL=UserLogin.js.map