import React, { useEffect, useState } from "react";
import { Close } from "@carbon/react/icons";
import { useOnClickOutside } from "../helpers";
import { HeaderGlobalAction, HeaderMenuItem, HeaderSideNavItems, SideNavItems, SideNavLink, SideNavMenu, SideNavMenuItem, } from "@carbon/react";
import { C3AppMenuIcon } from "../../../assets/c3-icons";
import { useC3Profile } from "../../c3-user-configuration/c3-profile-provider/c3-profile-provider";
import { useC3UserConfiguration } from "../../c3-user-configuration/c3-user-configuration-provider";
import { APPS } from "../../../utils/camunda";
import { NavWrapper, SideNav } from "./components";
export const C3NavigationAppBar = ({ app: appProps, appBar, forwardRef, navbar, }) => {
    const { currentApp, domain, analyticsTrack, currentClusterUuid } = useC3UserConfiguration();
    const { clusters, activeOrg, isEnabled } = useC3Profile();
    const [appBarOpen, setAppBarOpen] = useState(appBar.isOpen || false);
    const { setPanelRef: panelRef, setIconRef: iconRef } = useOnClickOutside(() => setAppBarOpen(false));
    const [appElements, setAppElements] = useState([]);
    if (!appBar.elements && !isEnabled)
        console.warn("No app elements and user config provided. Please provide at least one of them.");
    useEffect(() => {
        if (appBar.elements)
            return;
        const defaultElements = [];
        for (const app of APPS) {
            if (!domain || !currentApp || !activeOrg?.uuid)
                return;
            const element = {
                key: app,
                label: app.charAt(0).toUpperCase() + app.slice(1),
                active: currentApp === app,
                href: currentApp === app ? "#" : undefined,
                onClick: currentApp === app ? () => false : undefined,
            };
            if (app === currentApp &&
                ["console", "modeler"].includes(app) &&
                appProps.routeProps) {
                element.routeProps = appProps.routeProps;
            }
            else if (app === "console") {
                element.href = `https://console.${domain}/org/${activeOrg?.uuid}`;
            }
            else if (app === "modeler") {
                const hasPermission = activeOrg?.permissions?.org?.webide?.read;
                if (hasPermission) {
                    element.href = `https://modeler.${domain}/login?returnUrl=/org/${activeOrg?.uuid}`;
                }
            }
            else {
                const hasAppReadPermission = activeOrg?.permissions?.cluster?.[app]?.read;
                const clustersToRender = clusters?.filter(({ status, endpoints }) => status[app] === "Healthy" && endpoints[app] && hasAppReadPermission);
                if (clustersToRender?.length === 1) {
                    if (currentApp !== app)
                        element.href = clustersToRender?.[0].endpoints[app];
                }
                else if (clustersToRender && clustersToRender.length > 1) {
                    element.onClick = undefined;
                    element.subElements = clustersToRender.map((cluster, index) => ({
                        key: `${app}-${cluster.uuid}-${index}`,
                        label: cluster.name,
                        href: cluster.endpoints[app],
                        onClick: () => {
                            setAppBarOpen(false);
                            analyticsTrack?.(`${app}:open`, { currentApp: app });
                        },
                        isActive: currentApp === app && currentClusterUuid === cluster.uuid,
                    }));
                }
                else if (app === "identity") {
                    // no app-teaser for identity for now
                    continue;
                }
                else if (hasAppReadPermission) {
                    if (appBar.appTeaserRouteProps?.[app]) {
                        element.routeProps = appBar.appTeaserRouteProps?.[app];
                    }
                    else {
                        element.href = `https://${currentApp}.${domain}/org/${activeOrg?.uuid}/appTeaser/${app}`;
                    }
                }
            }
            if (element.href || element.routeProps || element.subElements)
                defaultElements.push(element);
        }
        setAppElements(defaultElements);
    }, [JSON.stringify(clusters), currentApp, domain]);
    const appBarElements = appBar.elements || (clusters ? appElements : null);
    return (React.createElement(React.Fragment, null,
        React.createElement(HeaderGlobalAction
        // eslint-disable-next-line
        // @ts-ignore
        , { 
            // eslint-disable-next-line
            // @ts-ignore
            ref: iconRef, "aria-label": "Camunda components", isActive: appBarOpen, onClick: () => {
                setAppBarOpen(!appBarOpen);
            }, tooltipAlignment: "start", 
            /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */
            /* @ts-ignore */
            leaveDelayMs: 100 }, appBarOpen ? React.createElement(Close, { size: 20 }) : React.createElement(C3AppMenuIcon, { size: 20 })),
        React.createElement(NavWrapper, null,
            React.createElement(SideNav, { ref: panelRef, "aria-label": appBar.ariaLabel || "Side Navigation", expanded: appBarOpen, isPersistent: false },
                React.createElement(SideNavItems, null,
                    React.createElement("li", null, navbar.elements.length > 0 && (React.createElement(HeaderSideNavItems, { hasDivider: true }, navbar.elements.map((element) => (React.createElement(HeaderMenuItem, { key: element.key, as: element.routeProps && forwardRef, isActive: element.isCurrentPage, ...element.routeProps, onClick: () => {
                            if (element.routeProps.onClick) {
                                element.routeProps.onClick();
                            }
                            if (appBar.closeOnClick !== false) {
                                setAppBarOpen(false);
                            }
                        } }, element.label)))))),
                    appBarElements &&
                        appBarElements.map((element) => {
                            if (element.subElements && element.subElements.length > 0) {
                                return (React.createElement(SideNavMenu, { large: true, title: element.label, key: element.key }, element.subElements.map((subElement) => (React.createElement(SideNavMenuItem, { as: subElement.routeProps && forwardRef, key: subElement.key, href: subElement.href, target: subElement.href ? subElement.target : undefined, isActive: subElement.isActive || subElement.active, ...subElement.routeProps, onClick: () => {
                                        if (subElement.onClick) {
                                            subElement.onClick();
                                        }
                                        if (subElement.routeProps?.onClick) {
                                            subElement.routeProps.onClick();
                                        }
                                        if (appBar.closeOnClick !== false) {
                                            setAppBarOpen(false);
                                        }
                                        if (appBar.elementClicked) {
                                            appBar.elementClicked(subElement.key);
                                        }
                                    } }, subElement.label)))));
                            }
                            else {
                                return (React.createElement(SideNavLink, { as: element.routeProps && forwardRef, key: element.key, large: true, isActive: element.active, ...element.routeProps, onClick: () => {
                                        if (element.onClick) {
                                            element.onClick();
                                        }
                                        if (element.routeProps?.onClick) {
                                            element.routeProps.onClick();
                                        }
                                        if (appBar.closeOnClick !== false) {
                                            setAppBarOpen(false);
                                        }
                                        if (appBar.elementClicked) {
                                            appBar.elementClicked(element.key);
                                        }
                                    }, href: element.href, target: element.href ? element.target : undefined }, element.label));
                            }
                        }))))));
};
