import React, { createContext, useContext, useEffect, useRef, useState, } from "react";
import { C3UserConfigurationContext } from "../c3-user-configuration-provider";
import { getUserTheme, updateTheme, getClusters, getOrgs, } from "../../../api/profile";
import { CarbonThemeProvider, resolveTheme, } from "./carbon-theme-provider";
export const defaultTheme = "light";
export const C3ProfileContext = createContext({
    isEnabled: false,
    theme: defaultTheme,
    orgs: null,
    activeOrg: null,
    reloadOrgs: () => undefined,
    removeOrg: () => undefined,
    clusters: null,
    reloadClusters: () => undefined,
    resolvedTheme: defaultTheme,
    onThemeChange: () => undefined,
});
export const C3ProfileProvider = ({ children }) => {
    const { decodedToken, decodedAudience, analyticsTrack, ...config } = useContext(C3UserConfigurationContext);
    const isEnabled = !!config;
    const themeRef = useRef(getUserTheme(config.userToken) || defaultTheme);
    const [resolvedTheme, setResolvedTheme] = useState(defaultTheme);
    const [orgs, setOrgs] = useState(null);
    const [activeOrg, setActiveOrg] = useState(null);
    const [clusters, setClusters] = useState(null);
    const isConfigValid = !!(config.userToken &&
        config.activeOrganizationId &&
        decodedAudience);
    const loadClusters = () => {
        if (!isConfigValid)
            return;
        getClusters(decodedAudience, config.userToken, config.activeOrganizationId).then(({ result }) => {
            if (result)
                setClusters(result);
        });
    };
    const loadOrgs = () => {
        if (!isConfigValid)
            return;
        getOrgs(decodedAudience, config.userToken).then(({ result: res }) => {
            setOrgs(res?.sort(({ name: a }, { name: b }) => a.localeCompare(b)) || null);
            setActiveOrg(res?.find((org) => org.uuid === config.activeOrganizationId) || null);
        });
    };
    const removeOrg = (orgId) => {
        if (orgs?.length === 1)
            return;
        setOrgs((orgs) => orgs?.filter((org) => org.uuid !== orgId) || null);
    };
    useEffect(() => {
        if (config?.activeOrganizationId) {
            const org = orgs?.find((org) => org.uuid === config.activeOrganizationId);
            if (org) {
                setActiveOrg(org);
            }
            else {
                loadOrgs();
            }
        }
        loadClusters();
    }, [
        config?.activeOrganizationId,
        JSON.stringify(decodedToken),
        decodedAudience,
    ]);
    useEffect(() => {
        const updateSystemTheme = ({ matches }) => {
            if (themeRef.current === "system")
                setResolvedTheme(matches ? "dark" : "light");
        };
        window
            .matchMedia("(prefers-color-scheme: dark)")
            .addEventListener("change", updateSystemTheme);
        return () => {
            window
                .matchMedia("(prefers-color-scheme: dark)")
                .removeEventListener("change", updateSystemTheme);
        };
    }, []);
    useEffect(() => {
        if (isEnabled && config.userToken && config.handleTheme) {
            const currentTheme = getUserTheme(config.userToken);
            if (currentTheme) {
                themeRef.current = currentTheme;
                setResolvedTheme(resolveTheme(currentTheme));
            }
        }
    }, [config?.userToken]);
    const onThemeChange = (newTheme) => {
        if (isEnabled) {
            themeRef.current = newTheme;
            setResolvedTheme(resolveTheme(newTheme));
            updateTheme({ ...config, theme: newTheme });
            analyticsTrack?.("theme:update", { value: newTheme });
        }
    };
    if (!isEnabled)
        return children;
    const content = config.handleTheme ? (React.createElement(CarbonThemeProvider, null, children)) : (children);
    return (React.createElement(C3ProfileContext.Provider, { value: {
            isEnabled,
            theme: themeRef.current,
            resolvedTheme,
            orgs,
            activeOrg,
            reloadOrgs: loadOrgs,
            clusters,
            reloadClusters: loadClusters,
            removeOrg,
            onThemeChange,
        } }, content));
};
export const useC3Profile = () => useContext(C3ProfileContext);
