import React, { useState, useCallback, useEffect, useRef, Suspense, lazy } from 'react';
import { makeStyles, IconButton, Popover, Typography, List, ListItem, ListItemIcon, ListItemText, Dialog, DialogTitle, DialogContent } from '@material-ui/core';
import { HelpOutline as HelpOutlineIcon, Chat as ChatIcon, Close as CloseIcon } from '@material-ui/icons';
import { useActions } from '../../hooks/useActions';
import { useTranslation } from 'react-i18next';
import { useUser } from '../../../src/utilities/auth/useUser';
import { apiMutate } from '../../utilities/useAxiosMutate';
import { ConfigService } from '../../configService';
// Lazy-load side sheets so they aren't imported until needed. Keep
// module-level lazy declarations so the imports are deduped and cached.
const UserFormSideSheet = lazy(() => import('./user/UserFormSideSheet'));
const SupportCaseSideSheet = lazy(() => import('../../UI/support/SupportCaseSideSheet'));
// Preload helpers (return the dynamic import promise). Calling these
// will start fetching the chunk in the background and populate the
// module cache so React.lazy resolves quickly later.
const preloadUserFormSideSheet = () => import('./user/UserFormSideSheet');
const preloadSupportCaseSideSheet = () => import('../../UI/support/SupportCaseSideSheet');
const useStyles = makeStyles((theme) => ({
    root: {
        display: 'flex'
    },
    popover: {
        padding: theme.spacing(2),
        maxWidth: 300
    },
    icon: {
        minWidth: 40
    },
    closeButton: {
        position: 'absolute',
        right: theme.spacing(1),
        top: theme.spacing(1),
        color: theme.palette.grey[500]
    },
    header: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    dialog: {
        minWidth: '80vw',
        minHeight: '80vh'
    }
}));
export const HelpCenter = () => {
    const classes = useStyles();
    const { t } = useTranslation();
    const { triggerAction } = useActions();
    const user = useUser();
    const productId = Number(ConfigService.config.UNITY_PRODUCT_ID);
    const udpaiAPI = ConfigService.config.UDPAI_API_BASE;
    const udpaisearch = ConfigService.config.AI_SEARCH_URL;
    const udpaisearchkey = ConfigService.config.AI_SEARCH_KEY;
    const udpaisearchindex = ConfigService.config.AI_SEARCH_INDEX_NAME;
    const [anchorEl, setAnchorEl] = useState(null);
    const [isSupportCaseSideSheetOpen, setSupportCaseSideSheetOpen] = useState(false);
    const [isUserFormOpen, setUserFormOpen] = useState(false);
    const [supportCaseHealthOk, setSupportCaseHealthOk] = useState(false);
    const hasPreloadedRef = useRef(false);
    const handleOpenPopover = (event) => {
        setAnchorEl(event.currentTarget);
        // Preload both side sheets in the background the first time the popover opens.
        // We assume that if the user opened the popover, they might open one of the sheets.
        if (!hasPreloadedRef.current) {
            hasPreloadedRef.current = true;
            // Start background fetches but don't await them.
            try {
                preloadUserFormSideSheet();
            }
            catch (e) {
                // ignore preload errors
            }
            try {
                preloadSupportCaseSideSheet();
            }
            catch (e) {
                // ignore preload errors
            }
        }
    };
    const handleClosePopover = () => {
        setAnchorEl(null);
    };
    const handleLaunchAction = useCallback(() => {
        setAnchorEl(null);
        triggerAction('CEE75B36-01B0-4FAC-9AE7-C1AC8A2A194F');
    }, [triggerAction]);
    const handleOpenSupportCaseSideSheet = () => {
        setSupportCaseSideSheetOpen(true);
        setAnchorEl(null);
    };
    const handleCloseSupportCaseSideSheet = () => {
        setSupportCaseSideSheetOpen(false);
    };
    const handleOpenUserForm = () => {
        setUserFormOpen(true); // Open UserForm modal
        setAnchorEl(null);
    };
    const handleCloseUserForm = () => {
        setUserFormOpen(false); // Close UserForm modal
    };
    const open = Boolean(anchorEl);
    const id = open ? 'help-center-popover' : undefined;
    // Conditions for rendering buttons
    // 2 assets, 41 sandbox, 51 assets, 53 mm, 68 timesheets
    const shouldShowAddUsers = (productId) => {
        const isValidProduct = [41, 53].includes(productId);
        const isSecurityApiConfigured = !!ConfigService.securityV1ApiUrl;
        const isValidUser = user.can.CAN_MANAGE_ROLES_USERS &&
            user.can.CAN_MANAGE_USERS &&
            user.can.CAN_VIEW_USERS;
        return isValidProduct && isSecurityApiConfigured && isValidUser;
    };
    const getSupportCaseStatus = useCallback(async () => apiMutate(ConfigService.productV1ApiUrl, `udpunitysupport/healthCheck`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [user === null || user === void 0 ? void 0 : user.currentTenantId]);
    const getSupportCaseStatusUnity = useCallback(async () => apiMutate(ConfigService.supportV1ApiUrl, `ServiceHealth/Support`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [user === null || user === void 0 ? void 0 : user.currentTenantId]);
    const showAddUsers = shouldShowAddUsers(productId);
    const shouldShowChatAssistant = [2, 41, 51, 68].includes(productId) &&
        udpaiAPI &&
        udpaisearch &&
        udpaisearchkey &&
        udpaisearchindex;
    const shouldShowSupportTicket = productId && supportCaseHealthOk;
    useEffect(() => {
        const supportCaseStatus = async () => {
            try {
                if (ConfigService.config.UNITY_PRODUCT_ID === "1") {
                    const response = await getSupportCaseStatusUnity();
                    setSupportCaseHealthOk((response === null || response === void 0 ? void 0 : response.status) === 200);
                }
                else {
                    const response = await getSupportCaseStatus();
                    setSupportCaseHealthOk((response === null || response === void 0 ? void 0 : response.status) === 200);
                }
            }
            catch (error) {
                setSupportCaseHealthOk(false);
            }
        };
        supportCaseStatus();
    }, [getSupportCaseStatus, getSupportCaseStatusUnity]);
    // Hide the entire help center if neither button should be rendered
    if (!showAddUsers && !shouldShowChatAssistant && !shouldShowSupportTicket) {
        return React.createElement("div", { id: "udpRecord-HelpCenter" });
    }
    return (React.createElement("div", { id: "udpRecord-HelpCenter", className: classes.root }, React.createElement(IconButton, { id: "udpRecord-HelpCenter-IconButton", "aria-controls": id, "aria-haspopup": "true", onClick: handleOpenPopover }, React.createElement(HelpOutlineIcon, { style: { color: 'white', opacity: 0.8 } })), React.createElement(Popover, { id: id, open: open, anchorEl: anchorEl, onClose: handleClosePopover, anchorOrigin: {
            vertical: 'bottom',
            horizontal: 'center'
        }, transformOrigin: {
            vertical: 'top',
            horizontal: 'center'
        } }, React.createElement("div", { className: classes.popover }, React.createElement("div", { className: classes.header }, React.createElement(Typography, { variant: "h6" }, t('Help')), React.createElement(IconButton, { size: "small", className: classes.closeButton, onClick: handleClosePopover }, React.createElement(CloseIcon, null))), React.createElement(List, { component: "nav", "aria-label": "Help options" }, showAddUsers && (React.createElement(ListItem, { button: true, id: "udpRecord-HelpCenter-AddUsers", onClick: handleOpenUserForm }, React.createElement(ListItemIcon, { className: classes.icon }, React.createElement(HelpOutlineIcon, null)), React.createElement(ListItemText, { primary: t('Add User') }))), shouldShowChatAssistant && (React.createElement(ListItem, { button: true, id: "udpRecord-HelpCenter-ChatAssistant", onClick: handleLaunchAction }, React.createElement(ListItemIcon, { className: classes.icon }, React.createElement(ChatIcon, null)), React.createElement(ListItemText, { primary: t('Chat Assistant') }))), shouldShowSupportTicket && (React.createElement(ListItem, { button: true, id: "udpRecord-HelpCenter-SupportTicket", onClick: handleOpenSupportCaseSideSheet }, React.createElement(ListItemIcon, { className: classes.icon }, React.createElement(HelpOutlineIcon, null)), React.createElement(ListItemText, { primary: t('Submit Support Ticket') })))))), React.createElement(Suspense, { fallback: null }, React.createElement(UserFormSideSheet, { open: isUserFormOpen, onClose: handleCloseUserForm })), React.createElement(Suspense, { fallback: null }, React.createElement(SupportCaseSideSheet, { open: isSupportCaseSideSheetOpen, onClose: handleCloseSupportCaseSideSheet, handleCloseSupportCaseSideSheet: handleCloseSupportCaseSideSheet, onSubmit: (values) => {
            console.log('Form submitted', values);
        }, initialValues: {} }))));
};
//# sourceMappingURL=HelpCenter.js.map