import React, { useState } from "react";
import { Button, FormLabel } from "@carbon/react";
import { Enterprise } from "@carbon/react/icons";
import C3NavigationSideBar from "../c3-navigation-sidebar/c3-navigation-sidebar";
import { SwitcherDivider } from "../c3-navigation-sidebar/components";
import { useOrgSidebarState } from "../c3-navigation-sidebar/c3-sidebar-state-provider";
import { useC3Profile } from "../../c3-user-configuration/c3-profile-provider/c3-profile-provider";
import { useC3UserConfiguration } from "../../c3-user-configuration/c3-user-configuration-provider";
import { ActiveOrgName, ActiveOrgNameWrapper, ActiveOrgWrapper, ActiveOrgWrapperCustom, ConfirmLeaveModal, ManageOrgOverflowMenu, } from "./components";
import { leaveOrganization } from "../../../api/organizations";
const C3OrgSidebar = ({ sideBar }) => {
    const { customElements, switchToOrg, manageOrg, elements, ...sideBarProps } = sideBar;
    const { isOpen, setIsOpen, scrollBarWidth } = useOrgSidebarState();
    const { userToken, decodedAudience, domain, analyticsTrack, setActiveOrgId } = useC3UserConfiguration();
    const { activeOrg, orgs, removeOrg } = useC3Profile();
    const isCustomized = Boolean(customElements?.activeOrganization);
    const [isConfirmLeaveModalOpen, setIsConfirmLeaveModalOpen] = useState(false);
    const [orgToLeave, setOrgToLeave] = useState(null);
    const [loadingStatus, setLoadingStatus] = useState("inactive");
    const isLastOrg = orgs?.length === 1;
    const canUserLeaveOrg = (orgPermissions) => (!orgPermissions.org?.users?.owner?.update &&
        orgs?.length &&
        orgs.length > 1) ||
        false;
    const canUserManageOrg = (orgPermissions) => orgPermissions.org?.settings?.read || false;
    const onManageCustomOrg = () => {
        if (sideBar.closeOnClick !== false)
            setIsOpen(false);
    };
    const onManageOrg = (orgId) => {
        setIsOpen(false);
        analyticsTrack?.("navBar:orgSettings:click", { orgId: activeOrg?.uuid });
        if (manageOrg) {
            manageOrg(orgId);
        }
        else {
            window.location.href = `https://console.${domain}/org/${orgId}/management`;
        }
    };
    const activeOrganization = customElements?.activeOrganization || {
        activeLabel: "Active organization",
        orgName: activeOrg?.name || "",
        action: {
            onClick: onManageCustomOrg,
            label: "Manage",
        },
        otherLabel: "Other organizations",
    };
    const switchOrg = (orgId, track) => {
        setActiveOrgId(orgId);
        if (track)
            analyticsTrack?.("navBar:orgSwitch:click", { orgId });
        switchToOrg?.(orgId);
        setIsOpen(false);
    };
    const orgElements = orgs
        ?.filter(({ uuid }) => uuid !== activeOrg?.uuid)
        .map((org) => ({
        key: org.uuid,
        label: org.name,
        onClick: () => switchOrg(org.uuid, true),
        overflowMenu: (React.createElement(ManageOrgOverflowMenu, { canManage: canUserManageOrg(org.permissions), canLeave: canUserLeaveOrg(org.permissions), isLastOrg: isLastOrg, orgName: org.name, onManage: () => onManageOrg(org.uuid), onRequestToLeave: () => {
                setOrgToLeave(org);
                setIsConfirmLeaveModalOpen(true);
            } })),
    }));
    const confirmLeaveOrg = async () => {
        if (orgToLeave && decodedAudience && userToken) {
            setLoadingStatus("active");
            const { success } = await leaveOrganization({
                token: userToken,
                audience: decodedAudience,
                orgId: orgToLeave.uuid,
            });
            setLoadingStatus(success ? "finished" : "error");
            if (success) {
                setIsConfirmLeaveModalOpen(false);
                removeOrg(orgToLeave.uuid);
            }
            if (orgToLeave.uuid === activeOrg?.uuid) {
                const newActiveOrg = orgs?.[0]?.uuid;
                if (newActiveOrg)
                    switchOrg(newActiveOrg);
            }
        }
    };
    const itemTabIndex = isOpen ? undefined : -1;
    return (React.createElement(C3NavigationSideBar, { sideBar: {
            ...sideBarProps,
            elements: elements || orgElements,
            ariaLabel: sideBarProps.ariaLabel || "Organization Sidebars",
        }, icon: React.createElement(Enterprise, { size: 20 }) }, (customElements?.activeOrganization || activeOrg) && (React.createElement(React.Fragment, null,
        isCustomized ? (React.createElement(ActiveOrgWrapperCustom, null,
            React.createElement("div", { style: {
                    overflow: "hidden",
                    display: "grid",
                    gap: "4px",
                } },
                React.createElement(FormLabel, null, activeOrganization.activeLabel),
                React.createElement(ActiveOrgName, { className: "textPrimary", title: activeOrganization.orgName, "$isCustomized": true }, activeOrganization.orgName)),
            React.createElement(Button, { size: "md", kind: "ghost", onClick: () => {
                    activeOrganization.action.onClick();
                    onManageCustomOrg();
                }, tabIndex: itemTabIndex }, activeOrganization.action?.label))) : (React.createElement(ActiveOrgWrapper, { "$scrollBarWidth": scrollBarWidth },
            React.createElement(FormLabel, null, activeOrganization.activeLabel),
            React.createElement(ActiveOrgNameWrapper, null,
                React.createElement(ActiveOrgName, { className: "textPrimary", title: activeOrganization.orgName }, activeOrganization.orgName),
                activeOrg?.uuid && domain && (React.createElement(ManageOrgOverflowMenu, { canManage: canUserManageOrg(activeOrg?.permissions), canLeave: canUserLeaveOrg(activeOrg?.permissions), orgName: activeOrg?.name || "", isLastOrg: isLastOrg, onManage: () => onManageOrg(activeOrg?.uuid), onRequestToLeave: () => {
                        setOrgToLeave(activeOrg);
                        setIsConfirmLeaveModalOpen(true);
                    } }))),
            React.createElement(ConfirmLeaveModal, { isOpen: isConfirmLeaveModalOpen, orgName: orgToLeave?.name || "", onConfirm: confirmLeaveOrg, onCancel: () => {
                    setIsConfirmLeaveModalOpen(false);
                    setOrgToLeave(null);
                }, loadingStatus: loadingStatus }))),
        ((sideBar.elements && sideBar.elements.length > 0) ||
            (orgElements && orgElements.length > 0)) && (React.createElement(React.Fragment, null,
            React.createElement(SwitcherDivider, null),
            React.createElement(FormLabel, { style: {
                    paddingTop: "15px",
                    paddingLeft: "1rem",
                    paddingBottom: ".25rem",
                } }, activeOrganization.otherLabel)))))));
};
export default C3OrgSidebar;
