import React, { useCallback, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { useAxiosGet } from '../utilities/useAxiosGet';
import { UtilitySideBar } from '../UI/utilityDisplay/UtilitySideBar';
import { makeStyles } from '@material-ui/core';
import { WorkflowTreeMenu } from './menus/WorkflowTreeMenu';
import { TreeViewModeEnums } from '../enums/unitySystemEnums';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { useShellStore } from '../stores/shellStore';
import { NodeLoader } from '../UI/feedback/NodeLoader';
import { APP_RIBBON_SPACE, useBuildEnvironment } from '../shell/ui/useBuildEnvironment';
import { WorkflowContent } from './WorkflowContent';
import { transformWorkflowPlayTree, updateWorkflowPlayNodeState } from '../utilities/workflow/workflowUtilities';
import { useUpdateSearchParams } from '../hooks/useUpdateSearchParams';
import { useUser } from '../utilities/auth/useUser';
import { apiMutate } from '../utilities/useAxiosMutate';
import { useSetLocationState } from '../hooks/useSetLocationState';
import { useTranslation } from 'react-i18next';
import { ConfigService } from '../configService';
const useStyles = makeStyles((theme) => ({
    root: {
        flex: 1,
        minHeight: ({ appRibbonSpace }) => `calc(100vh - ${appRibbonSpace + 56}px)`,
        display: 'grid',
        gridTemplateAreas: ['sidebar content'].map((line) => `"${line}"`).join(' '),
        gridTemplateColumns: 'auto 1fr',
        gridTemplateRows: 'auto 1fr'
    },
    sidebar: {
        gridArea: 'sidebar',
        marginRight: theme.spacing(1)
    },
    content: {
        gridArea: 'content',
        display: 'flex',
        flexDirection: 'column',
        position: 'relative',
        zIndex: 1,
        height: ({ appRibbonSpace }) => `calc(100vh - ${appRibbonSpace + 56}px)`,
        overflowY: 'auto'
    },
    menuContent: {
        marginTop: theme.spacing(1),
        height: ({ appRibbonSpace }) => `calc(100vh - ${appRibbonSpace + 116}px)`,
        overflowX: 'hidden'
    },
    loader: {
        marginRight: theme.spacing(1),
        marginLeft: theme.spacing(1)
    },
    loadingContent: {
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center'
    }
}));
export const WorkflowContainer = (props) => {
    const { playId, taskId, autoCollapseNav = true } = props;
    const buildEnv = useBuildEnvironment();
    const classes = useStyles(Object.assign(Object.assign({}, props), { appRibbonSpace: buildEnv ? APP_RIBBON_SPACE : 0 }));
    const location = useLocation();
    const updateSearchParams = useUpdateSearchParams();
    const user = useUser();
    const setLocationState = useSetLocationState();
    const { t } = useTranslation();
    const [menuItemsList, setMenuItemsList] = useState([]); // holds a list of trees
    const [selectedNode, setSelectedNode] = useState(null);
    const [sidebarExpanded, setSidebarExpanded] = useState(true);
    const [reloadFromPage, setReloadFromPage] = useState(false);
    const [workflow, setWorkflow] = useState(false);
    const state = location.state;
    let searchParamStr = location.search;
    let searchParams = new URLSearchParams(searchParamStr);
    const urlPlayId = location.pathname.replace('/workflowtask/', '');
    const udpPlayId = playId ||
        urlPlayId ||
        (state
            ? state.playId
            : searchParams.has('playId') === true
                ? searchParams.get('playId')
                : '');
    const udpTaskId = taskId ||
        (state
            ? state.taskId
            : searchParams.has('taskId') === true
                ? searchParams.get('taskId')
                : '');
    const [{ data: workflowPlay, loading: workflowPlayLoading }, reloadWorkflow] = useAxiosGet(ConfigService.builderV1ApiUrl, `workflow/play/${udpPlayId}`, {}, !!!udpPlayId, false);
    const [{ data: users }] = useAxiosGet(ConfigService.securityV1ApiUrl, `users?tenantId=${(user === null || user === void 0 ? void 0 : user.currentTenantId) || ''}`, {}, !!!(user === null || user === void 0 ? void 0 : user.currentTenantId));
    const [{ data: groups }] = useAxiosGet(ConfigService.tenantV1ApiUrl, `groups?tenantId=${(user === null || user === void 0 ? void 0 : user.currentTenantId) || ''}&productId=${ConfigService.config.UNITY_PRODUCT_ID}`, {}, !!!(user === null || user === void 0 ? void 0 : user.currentTenantId));
    // const getNodeState = useCallback(
    //   async (nodeId) =>
    //     apiMutate(
    //       ConfigService.builderV1ApiUrl,
    //       `workflow/play/${udpPlayId}/node/${nodeId}/state`,
    //       {
    //         method: 'get'
    //       }
    //     ),
    //   [udpPlayId]
    // );
    const { setSubHeaderActionHasChildren, setNavigationExpanded } = useShellStore();
    const handleReloadWorkflow = useCallback(async () => {
        setReloadFromPage(true);
        await reloadWorkflow();
        setReloadFromPage(false);
    }, [reloadWorkflow]);
    const handleSelectedNode = useCallback(async (node, menuIndex) => {
        var _a;
        if (node.isSelectable) {
            setSelectedNode(node);
            await handleReloadWorkflow();
            if ((_a = node === null || node === void 0 ? void 0 : node.properties) === null || _a === void 0 ? void 0 : _a.playSceneId) {
                updateSearchParams({ taskId: node.properties.playSceneId });
            }
        }
    }, [updateSearchParams, handleReloadWorkflow]);
    const handleDropNode = useCallback((sourceNode, targetNode, sourceNodeMenuIndex, targetNodeMenuIndex) => {
        // TODO: Implement if we need to for next Phase
    }, []);
    const handleSidebarExpandClick = useCallback(() => {
        setSidebarExpanded((expanded) => !expanded);
    }, []);
    useEffect(() => {
        if (workflowPlay) {
            setWorkflow(workflowPlay);
        }
    }, [workflowPlay]);
    // Setting location state label so that if this page was saved to favorites
    // we can determine the bread crumb
    useEffect(() => {
        setLocationState({ label: t('Workflow') });
    }, [setLocationState, t]);
    // this is used for updating the state node for page use
    useEffect(() => {
        if (workflow) {
            setSelectedNode((prevNode) => {
                var _a, _b;
                if (!!prevNode) {
                    const foundNode = (_b = (_a = workflow.workflowPlayNode) === null || _a === void 0 ? void 0 : _a.children) === null || _b === void 0 ? void 0 : _b.find((child) => child.id === prevNode.id);
                    if (!!foundNode) {
                        const updatedNode = Object.assign({}, prevNode);
                        // TODO: using this to update state for now but may need to update
                        // other properties of the selected node when we pull workflow tree
                        updatedNode.properties.state = foundNode.state;
                        return updatedNode;
                    }
                    else {
                        return prevNode;
                    }
                }
            });
        }
    }, [workflow]);
    useEffect(() => {
        if (workflow) {
            const list = [];
            const updatedMenu = transformWorkflowPlayTree(workflow.workflowPlayNode);
            if (updatedMenu) {
                list.push(updatedMenu);
            }
            setMenuItemsList(list);
        }
    }, [workflow]);
    useEffect(() => {
        var _a;
        if (!selectedNode) {
            const menu = menuItemsList[0];
            // Use Task Id to find the first matching node in tree
            if (menu) {
                if (!!udpTaskId) {
                    const matchingTaskNode = menu.children.find((child) => {
                        var _a;
                        return ((_a = child === null || child === void 0 ? void 0 : child.properties) === null || _a === void 0 ? void 0 : _a.playSceneId) === udpTaskId;
                    });
                    setSelectedNode(matchingTaskNode || menu.children[0] || null);
                }
                else {
                    const firstSelectableMenuItem = (_a = menu === null || menu === void 0 ? void 0 : menu.children) === null || _a === void 0 ? void 0 : _a.find((item) => item.isSelectable);
                    setSelectedNode(firstSelectableMenuItem || null);
                }
                if (autoCollapseNav) {
                    setNavigationExpanded(false);
                }
            }
        }
    }, [
        udpTaskId,
        menuItemsList,
        selectedNode,
        setNavigationExpanded,
        autoCollapseNav
    ]);
    useEffect(() => {
        setSubHeaderActionHasChildren(false);
    }, [setSubHeaderActionHasChildren]);
    // useEffect(() => {
    //   if (selectedNode) {
    //     const getState = async () => {
    //       const response = await getNodeState(selectedNode.id);
    //       if (response.status === 200) {
    //         setMenuItemsList((prevMenuList) => {
    //           let updatedList = [];
    //           prevMenuList.forEach((menu) => {
    //             const updatedMenu = updateWorkflowPlayNodeState(
    //               menu,
    //               selectedNode.id,
    //               response.data
    //             );
    //             updatedList.push(updatedMenu);
    //           });
    //           return updatedList;
    //         });
    //       }
    //     };
    //     getState();
    //   }
    // }, [selectedNode, getNodeState]);
    return (React.createElement(DndProvider, { backend: HTML5Backend }, React.createElement("div", { className: classes.root }, React.createElement("div", { className: classes.sidebar }, React.createElement(UtilitySideBar, { title: 'Workflow', isUsingChildren: true, resizable: true, removePadding: true, removeTopLayoutUnit: true, onUtilitySidebarToggleExpandClick: handleSidebarExpandClick, collapsedWidth: 64 }, React.createElement("div", { className: classes.menuContent, key: playId }, (menuItemsList === null || menuItemsList === void 0 ? void 0 : menuItemsList.length) > 0 &&
        (!workflowPlayLoading || reloadFromPage) &&
        menuItemsList.map((menuItems, index) => (React.createElement("div", { key: menuItems.id, className: classes.nodeContainer }, React.createElement(WorkflowTreeMenu, { menuItems: menuItems, onSelectNode: handleSelectedNode, onDropNode: handleDropNode, menuIndex: index, selectedNodeId: selectedNode === null || selectedNode === void 0 ? void 0 : selectedNode.id, selectedNodeParentId: selectedNode === null || selectedNode === void 0 ? void 0 : selectedNode.parentId, sidebarExpanded: sidebarExpanded, treeViewMode: TreeViewModeEnums.Classic })))), workflowPlayLoading && !reloadFromPage && (React.createElement("div", { className: classes.loader }, React.createElement(NodeLoader, { loading: workflowPlayLoading })))))), React.createElement("div", { className: classes.content }, React.createElement(WorkflowContent, { selectedNode: selectedNode, workflow: workflow, reloadWorkflow: handleReloadWorkflow, users: users, groups: groups })))));
};
export default WorkflowContainer;
//# sourceMappingURL=WorkflowContainer.js.map