import { ActionableNotification, ComposedModal, Layer, ModalBody, ModalHeader, } from "@carbon/react";
import React, { useEffect, useRef, useState } from "react";
import { HelpCenter } from "./help-center";
import { defaultHelpCenterConfig } from "./defaultHelpCenterConfig";
import { C3OnboardingSurvey } from "../c3-onboarding-survey/c3-onboarding-survey";
import { getConfig, updatePersona } from "../../api/help-center";
import { useC3UserConfiguration } from "../c3-user-configuration/c3-user-configuration-provider";
import { defaultTheme, useC3Profile, } from "../c3-user-configuration/c3-profile-provider/c3-profile-provider";
import { resolveTheme, } from "../c3-user-configuration/c3-profile-provider/carbon-theme-provider";
import { useC3HelpCenter } from "./c3-help-center-provider";
import styled from "styled-components";
import { ErrorBoundary } from "react-error-boundary";
const StyledComposedModal = styled(ComposedModal) `
	.cds--modal-scroll-content {
		mask-image: none;
	}
`;
export const C3HelpCenter = ({ autoStartSurvey, origin, flags, onRequestClose, mixpanelTrack: customMixpanelTrack, onRequestOpen, theme, onPersonaChange, activeTab, }) => {
    const { isHelpCenterOpen: isOpen, setIsHelpCenterOpen, setShowHintOnClose, } = useC3HelpCenter();
    const { userToken, decodedToken, activeOrganizationId, handleTheme, decodedAudience, analyticsTrack, currentApp, } = useC3UserConfiguration();
    const { theme: themeConfig, isEnabled, reloadClusters } = useC3Profile();
    const themeHandlingEnabled = isEnabled && !!handleTheme && !!themeConfig;
    const themeRef = useRef();
    const [resolvedTheme, setResolvedTheme] = useState(defaultTheme);
    const [persona, setPersona] = useState(undefined);
    const [userId, setUserId] = useState("");
    const [helpCenterConfig, setHelpCenterConfig] = useState(defaultHelpCenterConfig);
    const [email, setEmail] = useState("");
    const [showSurvey, setShowSurvey] = useState(autoStartSurvey);
    if (!origin && !currentApp)
        console.warn("No app provided to the help center. Please provide the `currentApp` prop to the `C3UserConfigurationProvider`.");
    const hostApp = origin || currentApp === "modeler" ? "webmodeler" : currentApp || "console";
    const mixpanelTrack = (event, data) => {
        if (customMixpanelTrack) {
            customMixpanelTrack(event, data);
        }
        else if (analyticsTrack) {
            analyticsTrack(event, data);
        }
    };
    useEffect(() => {
        const updateResolvedTheme = ({ matches }) => {
            if (themeRef.current === "system") {
                setResolvedTheme(matches ? "light" : "dark");
            }
        };
        window
            .matchMedia("(prefers-color-scheme: light)")
            .addEventListener("change", updateResolvedTheme);
        return () => {
            window
                .matchMedia("(prefers-color-scheme: light)")
                .removeEventListener("change", updateResolvedTheme);
        };
    }, []);
    useEffect(() => {
        const newTheme = themeHandlingEnabled ? themeConfig : theme;
        themeRef.current = newTheme;
        setResolvedTheme(resolveTheme(newTheme || "light"));
    }, [theme, themeConfig, isOpen]);
    const fetchConfig = async () => {
        if (!userToken || !decodedAudience)
            return;
        const { result: config } = await getConfig(userToken, decodedAudience, activeOrganizationId);
        setHelpCenterConfig(config || defaultHelpCenterConfig);
    };
    const isFirstLoad = useRef(true);
    const fetchData = async () => {
        if (!userToken || !decodedToken || !decodedAudience)
            return;
        const { userId, meta, persona: tokenPersona } = decodedToken;
        if (tokenPersona !== undefined) {
            setPersona(tokenPersona);
            if (tokenPersona.wasShown) {
                setShowSurvey(false);
            }
        }
        else {
            setPersona({ wasShown: false });
        }
        if (meta)
            setEmail(meta.email);
        if (userId)
            setUserId(userId);
        if (autoStartSurvey && !tokenPersona?.wasShown) {
            setIsHelpCenterOpen(true);
            onRequestOpen?.();
        }
        await fetchConfig();
        isFirstLoad.current = false;
    };
    React.useEffect(() => {
        fetchData();
    }, [JSON.stringify(decodedToken), decodedAudience]);
    useEffect(() => {
        if (isFirstLoad.current ||
            !userToken ||
            !decodedAudience ||
            !persona?.complete)
            return;
        fetchConfig();
        reloadClusters();
    }, [persona?.complete]);
    useEffect(() => {
        if (isFirstLoad.current || !activeOrganizationId)
            return;
        fetchConfig();
        reloadClusters();
    }, [activeOrganizationId]);
    React.useEffect(() => {
        const tabs = helpCenterConfig.tabs;
        const firstTab = tabs[0]?.id;
        if (isOpen) {
            if (autoStartSurvey && !persona?.wasShown) {
                setShowHintOnClose(true);
            }
            if (persona && !persona.wasShown && decodedAudience) {
                updatePersona({
                    newPersona: { ...persona, wasShown: true },
                    audience: decodedAudience,
                    accessToken: userToken,
                    orgId: activeOrganizationId,
                    userId,
                });
                setPersona({ wasShown: true });
            }
            mixpanelTrack?.("helpcenter:open", {
                to: activeTab ?? firstTab,
                from: origin,
            });
        }
    }, [isOpen]);
    const onRequestRetakeSurvey = () => {
        if (!userToken || !activeOrganizationId || !decodedAudience)
            return;
        const newPersona = {
            ...persona,
            ...{ nextStep: 0, complete: false },
        };
        setPersona(newPersona);
        updatePersona({
            newPersona,
            audience: decodedAudience,
            accessToken: userToken,
            orgId: activeOrganizationId,
            userId,
        });
        onPersonaChange?.(newPersona);
        setShowSurvey(true);
    };
    const onRequestResumeSurvey = () => {
        if (!userToken || !activeOrganizationId || !decodedAudience)
            return;
        const newPersona = { ...persona, ...{ complete: false, wasShown: true } };
        setPersona(newPersona);
        updatePersona({
            newPersona,
            audience: decodedAudience,
            accessToken: userToken,
            orgId: activeOrganizationId,
            userId,
        });
        onPersonaChange?.(newPersona);
        setShowSurvey(true);
    };
    const onRequestSkipSurvey = () => {
        if (!userToken || !activeOrganizationId || !decodedAudience)
            return;
        const newPersona = { ...persona, ...{ complete: false, wasShown: true } };
        setPersona(newPersona);
        updatePersona({
            newPersona,
            audience: decodedAudience,
            accessToken: userToken,
            orgId: activeOrganizationId,
            userId,
        });
        onPersonaChange?.(newPersona);
        setShowSurvey(false);
    };
    const personaCallback = (newPersona) => {
        setPersona(newPersona);
        onPersonaChange?.(newPersona);
        if (newPersona.complete) {
            setShowSurvey(false);
        }
    };
    const closeFn = () => {
        setIsHelpCenterOpen(false);
        if (persona && userToken && activeOrganizationId && decodedAudience) {
            updatePersona({
                newPersona: persona,
                audience: decodedAudience,
                accessToken: userToken,
                orgId: activeOrganizationId,
                userId,
            });
        }
        onRequestClose?.();
        fetchConfig();
        reloadClusters();
        // wait for modal transition
        setTimeout(() => {
            setShowSurvey(false);
        }, 400);
    };
    return (React.createElement(Layer, null,
        React.createElement(StyledComposedModal, { open: isOpen, size: "lg", onClose: closeFn, className: "help-center", "aria-label": "HelpCenter", style: showSurvey || !persona?.wasShown
                ? { backgroundColor: "rgba(22,22,22, 0.8)" }
                : {} },
            React.createElement(ErrorBoundary, { fallbackRender: () => (React.createElement(React.Fragment, null,
                    React.createElement(ModalHeader, { title: "Help Center", closeModal: closeFn }),
                    React.createElement(ModalBody, null,
                        React.createElement(ActionableNotification, { inline: true, hideCloseButton: true, lowContrast: true, kind: "error", title: "Something went wrong.", subtitle: "Try reloading the page.", actionButtonLabel: "Reload", onActionButtonClick: () => window.location.reload() })))) }, showSurvey || !persona?.wasShown ? (React.createElement(C3OnboardingSurvey, { personaCallback: personaCallback, persona: persona, mixpanelTrack: mixpanelTrack, onRequestClose: closeFn, onRequestSkip: onRequestSkipSurvey, theme: resolvedTheme, origin: hostApp, modal: true })) : (React.createElement(HelpCenter, { configuration: helpCenterConfig, persona: persona, audience: decodedAudience || "", flags: flags, onRequestResumeSurvey: onRequestResumeSurvey, onRequestRetakeSurvey: onRequestRetakeSurvey, onRequestClose: closeFn, mixpanelTrack: mixpanelTrack, email: email, theme: resolvedTheme, origin: hostApp, initialTab: activeTab }))))));
};
