import { useEffect, useState, useRef } from 'react';
import { action } from '@storybook/addon-actions';
import { CaseHierarchy } from '@pega/cosmos-react-work';
import { createUID, treeHelpers } from '@pega/cosmos-react-core';
export default {
    title: 'Work/CaseHierarchy',
    component: CaseHierarchy
};
export const CaseHierarchyDemo = (args) => {
    const [currentNodeId, setCurrentNodeId] = useState(args.currentCaseId);
    const [allNodes, setAllNodes] = useState([]);
    const allNodesRef = useRef([]);
    const [loading, setLoading] = useState(args.loading ?? true);
    useEffect(() => {
        const timer = setTimeout(() => {
            setLoading(false);
        }, 500);
        return () => clearTimeout(timer);
    }, []);
    const getMockNodes = ({ length = args.numChildCases, parent = true } = {}) => {
        return Array.from({ length }, (_, i) => {
            const isParent = parent && i !== 2;
            const id = createUID();
            const generateRandomCaseId = () => 'EPIC-'.concat(String(Math.floor(100000 + Math.random() * 900000)));
            const generateRandomChildCaseId = () => 'US-'.concat(String(Math.floor(100000 + Math.random() * 900000)));
            return {
                id,
                label: isParent ? 'Parent Case Type' : 'Child Case Type',
                secondary: isParent ? generateRandomCaseId() : generateRandomChildCaseId(),
                nodes: isParent ? [] : undefined,
                onClick: isParent
                    ? undefined
                    : nodeId => {
                        action(`Action for node: ${nodeId}`)();
                    },
                href: id === currentNodeId ? undefined : `#${id}`,
                onPreview: isParent ? () => { } : undefined,
                onLoadMore: isParent && args.loadMore
                    ? () => {
                        const currentNode = treeHelpers.getNode(allNodesRef.current, id);
                        if (currentNode && currentNode.nodes) {
                            currentNode.nodes = [
                                ...currentNode.nodes,
                                ...getMockNodes({ length: args.numChildCases, parent: false })
                            ];
                            setAllNodes([...allNodesRef.current]);
                        }
                    }
                    : undefined
            };
        });
    };
    const getNodesCount = (nodes) => {
        let nodeCount = 0;
        treeHelpers.forEachNode(nodes, () => {
            nodeCount += 1;
        });
        return nodeCount;
    };
    useEffect(() => {
        allNodesRef.current = allNodes;
    }, [allNodes]);
    useEffect(() => {
        setAllNodes(() => {
            if (args.nodes)
                return args.nodes;
            return getMockNodes({ length: args.numCases });
        });
    }, []);
    useEffect(() => {
        if (args.nodes)
            return;
        if (args.numCases > 0) {
            setAllNodes(getMockNodes({ length: args.numCases }));
        }
    }, [args.numCases, args.numChildCases, args.nodes, args.loadMore]);
    const loadChildNodes = (id) => {
        setTimeout(() => {
            setAllNodes(tree => {
                return treeHelpers.mapNode(tree, id, node => {
                    return {
                        ...node,
                        loading: false,
                        nodes: [...(node.nodes ?? []), ...getMockNodes()]
                    };
                });
            });
        }, 1000);
    };
    return (<CaseHierarchy heading={args.heading ?? 'Case relationships'} icon={args.icon ?? 'folder-nested'} lined={args.lined} error={args.error} currentCaseId={args.currentCaseId} count={getNodesCount(allNodes)} nodes={allNodes} loading={args.loading ? args.loading : loading} onLoadMore={args.loadMore
            ? () => setAllNodes([...allNodesRef.current, ...getMockNodes({ length: args.numChildCases })])
            : undefined} onNodeClick={(id, e) => {
            e.preventDefault();
            setCurrentNodeId(id);
        }} onNodeToggle={id => {
            const clickedNode = treeHelpers.getNode(allNodes, id);
            if (!clickedNode?.nodes)
                return;
            setAllNodes(tree => treeHelpers.mapNode(tree, id, node => {
                return {
                    ...node,
                    expanded: !node.expanded,
                    loading: node.nodes?.length === 0
                };
            }));
            if (clickedNode?.nodes?.length > 0)
                return;
            loadChildNodes(id);
        }} selectableParents/>);
};
CaseHierarchyDemo.args = {
    loadMore: true,
    lined: false,
    numCases: 3,
    numChildCases: 3
};
CaseHierarchyDemo.argTypes = {
    loadMore: { control: { type: 'boolean' } },
    lined: { control: { type: 'boolean' } },
    numCases: { control: { type: 'number' } },
    numChildCases: { control: { type: 'number' } }
};
//# sourceMappingURL=CaseHierarchy.stories.jsx.map