import { initializeUserflow } from "@insite/shell/Components/Shell/Userflow";
import {
    AdminOptions,
    getAdminOptions,
    getCurrentUser,
    UserProfileViewModel,
} from "@insite/shell/Services/AdminService";
import * as React from "react";
import { createContext, PropsWithChildren, useContext, useEffect, useState } from "react";

export const AdminContext = createContext<{
    options: AdminOptions;
    currentUser: UserProfileViewModel;
}>({} as any);

export const useAdminContext = () => {
    return useContext(AdminContext);
};

export const AdminContextProvider = (props: PropsWithChildren<any>) => {
    const [options, setOptions] = useState<AdminOptions | undefined>();
    const [currentUser, setCurrentUser] = useState<UserProfileViewModel | undefined>();

    useEffect(() => {
        getAdminOptions().then(options => {
            setOptions(options);
        });
    }, []);

    useEffect(() => {
        getCurrentUser().then(({ userProfile }) => {
            setCurrentUser(userProfile);
        });
    }, []);

    if (!options || !currentUser) {
        return null;
    }

    initializeUserflow(options, currentUser);

    return <AdminContext.Provider value={{ options, currentUser }}>{props.children}</AdminContext.Provider>;
};
