import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { User } from "@feedloop/icon";
import { Box, Button, Center, Icon, Input, Menu, MenuItem, MenuList, Popover, PopoverArrow, PopoverContent, PopoverTrigger, Portal, } from "@chakra-ui/react";
import React from "react";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import qore from "@qorebase/app-runtime/src/hooks/qore";
import EditorContext from "@qorebase/app-runtime/src/EditorContext";
import { QoreClient } from "@qorebase/client";
import useSWR from "swr";
import { useNavigate } from "react-router";
import { css } from "@emotion/react";
const identifierField = "external_id";
export default function LoginAsUser() {
    const { user, refetch: refetchUser } = qore.useCurrentUser();
    const config = RuntimeContext.useSelectState((state) => state.config);
    const qoreAdminConfig = EditorContext.useSelectState((state) => state.qoreDataConfig);
    const client = React.useMemo(() => new QoreClient(qoreAdminConfig), [qoreAdminConfig]);
    const [search, setSearch] = React.useState("");
    const users = useSWR(["qore users"], () => client
        .table("users")
        .readRows()
        .toPromise()
        .then((res) => { var _a; return (_a = res.data) === null || _a === void 0 ? void 0 : _a.nodes; }));
    const filteredUsers = React.useMemo(() => {
        var _a;
        return (((_a = users.data) === null || _a === void 0 ? void 0 : _a.filter((user) => { var _a; return (_a = user[identifierField]) === null || _a === void 0 ? void 0 : _a.startsWith(search); })) || []);
    }, [users, search]);
    const handleSearch = React.useCallback((e) => {
        setSearch(e.currentTarget.value);
    }, []);
    const handleLogout = React.useCallback(() => {
        localStorage.removeItem(`${config.projectID}_user_token`);
        refetchUser();
    }, [config.projectID]);
    const handleResetSearch = React.useCallback(() => {
        setSearch("");
    }, []);
    return (_jsx(Center, { children: _jsxs(Popover, Object.assign({ placement: "bottom", isLazy: true }, { children: [_jsx(PopoverTrigger, { children: _jsx(Button, Object.assign({ variant: "ghost", size: "sm", rightIcon: _jsx(Icon, { as: User }) }, { children: user ? (_jsxs("span", { children: ["Viewing as ", _jsx("strong", { children: user[identifierField] })] })) : ("View as person") })) }), _jsx(Portal, { children: _jsxs(PopoverContent, Object.assign({ w: "320px", h: "240px" }, { children: [_jsx(PopoverArrow, {}), _jsxs(Box, Object.assign({ position: "relative", height: "full" }, { children: [_jsx(Box, Object.assign({ position: "absolute", top: "0", left: "0", right: "0", height: "64px", padding: "10px" }, { children: _jsx(Input, { value: search, fontSize: "reg", size: "sm", placeholder: "Search user", onChange: handleSearch, minWidth: "298px" }) })), _jsx(Box, Object.assign({ position: "absolute", bottom: "0", left: "0", right: "0", top: "50px", overflowY: "auto", overflowX: "hidden", px: "10px", css: css `
                  ::-webkit-scrollbar {
                    width: 6px;
                    height: 8px;
                  }

                  ::-webkit-scrollbar-thumb {
                    background: rgba(0, 0, 0, 0.2);
                    border-radius: 4px;
                  }
                ` }, { children: _jsx(Box, Object.assign({ position: "relative" }, { children: _jsx(Menu, Object.assign({ isOpen: true, isLazy: true }, { children: _jsxs(MenuList, Object.assign({ width: "100%" }, { children: [!!user && (_jsx(MenuItem, Object.assign({ onClick: handleLogout }, { children: "Logout" }), "logout")), filteredUsers.map((user) => (_jsx(UserMenuItem, { user: user, client: client, onResetSearch: handleResetSearch }, user.id)))] })) })) })) }))] }))] })) })] })) }));
}
function UserMenuItem({ user, client, onResetSearch }) {
    const projectID = RuntimeContext.useSelectState((state) => state.config.projectID);
    const loggedInPage = RuntimeContext.useSelectState((state) => { var _a; return (_a = state.config.initialPage) === null || _a === void 0 ? void 0 : _a.loggedInPage; });
    const navigate = useNavigate();
    const { refetch } = qore.useCurrentUser();
    const handleClick = React.useCallback(() => __awaiter(this, void 0, void 0, function* () {
        onResetSearch();
        const token = yield client.authenticate(user[identifierField], undefined);
        localStorage.setItem(`${projectID}_user_token`, token);
        loggedInPage && navigate(`/page/${loggedInPage}`);
        refetch();
    }), [user, projectID, client, refetch, loggedInPage]);
    return (_jsxs(MenuItem, Object.assign({ onClick: handleClick }, { children: ["Login as ", user[identifierField]] })));
}
//# sourceMappingURL=LoginAsUser.js.map