import { useState, useMemo, useRef } from 'react';
import { AppShell, AppShellList, Icon, registerIcon, useModalManager, useAfterInitialEffect, windowIsAvailable, ThemeOverride, menuHelpers } from '@pega/cosmos-react-core';
import * as bellSolidIcon from '@pega/cosmos-react-core/lib/components/Icon/icons/bell-solid.icon';
import * as clockSolidIcon from '@pega/cosmos-react-core/lib/components/Icon/icons/clock-solid.icon';
import { recentSearches, searchResults } from '../SearchInput/SearchInput.mocks';
import { MultiStepModal } from '../MultiStepForm/MultiStepForm.mocks';
import { defaultCases, defaultLinks, defaultMainContent, defaultNotifications, defaultRecents, operatorData } from './AppShell.mocks';
registerIcon(bellSolidIcon, clockSolidIcon);
export default {
    title: 'Core/App Shell',
    component: AppShell,
    excludeStories: ['ConfigurableAppShell'],
    parameters: {
        layout: 'fullscreen'
    }
};
export const AppShellDemo = (args) => {
    const [activeAppName, setActiveAppName] = useState(args.appName || 'UI Audit');
    const caseLinks = args.caseLinks || defaultLinks;
    const showSearch = args.withSearch !== undefined ? args.withSearch : true;
    const { create: createModal } = useModalManager();
    const [links, setLinks] = useState(caseLinks);
    const [notifications, setNotifications] = useState(defaultNotifications);
    const [recents, setRecents] = useState(args.recentItems || defaultRecents);
    const [numNewNotifications, setNumNewNotifications] = useState(notifications.filter(x => x.unread).length);
    const [searchVal, setSearchVal] = useState('');
    const [searchLoading, setSearchLoading] = useState(false);
    const [results, setResults] = useState([]);
    const [searchTimeout, setSearchTimeout] = useState();
    const [progress, setProgress] = useState('');
    useAfterInitialEffect(() => {
        setLinks(caseLinks);
    }, [caseLinks]);
    const addHandlersToLinks = (appShellLinks) => {
        return (appShellLinks || []).map(link => ({
            ...link,
            onClick(e) {
                e.preventDefault();
                setLinks((prevLinks = []) => {
                    return prevLinks.map(prevLink => {
                        return {
                            ...prevLink,
                            active: prevLink.name === link.name
                        };
                    });
                });
                setProgress(`${link.name} loading...`);
                setTimeout(() => {
                    args.onLinkClick?.(link.name);
                    setProgress('');
                }, 1000);
            },
            links: link.links ? addHandlersToLinks(link.links) : undefined
        }));
    };
    const linksWithHandlers = useMemo(() => {
        return addHandlersToLinks(links);
    }, [links]);
    const defaultCreateLinks = [
        'Data Analyst interview',
        'Designer interview',
        'Product Manager interview',
        'Sales Representative interview',
        'Software Engineer interview'
    ].map(name => ({
        name,
        onClick: () => {
            createModal(MultiStepModal, { heading: name, stepIndicator: 'horizontal' });
        }
    }));
    const handleNotificationClick = (passedId) => {
        setNotifications(cur => cur.map(({ id, unread, ...item }) => ({
            id,
            unread: passedId === id ? false : unread,
            ...item
        })));
    };
    const handlePinToggle = (passedId) => {
        setRecents(cur => cur.map(({ id, pinned, ...item }) => ({
            id,
            pinned: passedId === id ? !pinned : pinned,
            ...item
        })));
    };
    const onSearch = (val) => {
        setSearchVal(val);
        if (searchTimeout) {
            clearTimeout(searchTimeout);
            setSearchTimeout(null);
        }
        setResults([]);
        if (val) {
            setSearchLoading(true);
            const timeout = setTimeout(() => {
                setSearchLoading(false);
                setResults(searchResults.filter(res => res.primary.includes(val)));
            }, 1000);
            setSearchTimeout(timeout);
        }
    };
    const notificationViewItems = [
        {
            id: '234',
            items: args.notificationsEmpty ? [] : notifications,
            loading: args.notificationsLoading,
            onItemClick: handleNotificationClick,
            viewAll: {
                href: '#'
            },
            emptyText: 'No notifications'
        }
    ];
    const recentViewItems = [
        {
            id: '456',
            items: recents.filter(x => x.pinned),
            loading: args.pinsLoading,
            onItemPinToggle: handlePinToggle,
            viewAll: {
                href: '#'
            },
            displayPins: true,
            headingText: 'Pinned items',
            emptyText: 'No pinned items'
        },
        {
            id: '789',
            items: args.recentsEmpty ? [] : recents,
            loading: args.recentsLoading,
            onItemPinToggle: handlePinToggle,
            viewAll: {
                href: '#'
            },
            displayPins: true,
            headingText: 'Recently viewed',
            emptyText: 'No recents'
        }
    ];
    const [contexts, setContexts] = useState([
        {
            id: '1',
            primary: activeAppName,
            selected: true,
            visual: <Icon name='app'/>
        },
        {
            id: '2',
            primary: 'BI Warehouse',
            selected: false,
            visual: <Icon name='cloud'/>
        }
    ]);
    const newNotificationCountTimerRef = useRef(NaN);
    const defaultUtils = [
        {
            name: 'Notifications',
            visual: <Icon name='bell-solid'/>,
            count: args.notificationsEmpty ? 0 : numNewNotifications,
            drawerView: <AppShellList listView={notificationViewItems}/>,
            onDrawerOpen: () => {
                clearInterval(newNotificationCountTimerRef.current);
                setNumNewNotifications(0);
            },
            onDrawerClose: () => {
                if (windowIsAvailable) {
                    newNotificationCountTimerRef.current = window.setInterval(() => {
                        setNumNewNotifications(cur => cur + 2);
                    }, 60000);
                }
            }
        },
        {
            name: 'Recents',
            visual: <Icon name='clock-solid'/>,
            drawerView: <AppShellList listView={recentViewItems}/>
        }
    ];
    return (<AppShell contextSwitcher={{
            contexts,
            onContextClick: (id) => {
                setActiveAppName(menuHelpers.getItem(contexts, id).primary);
                setContexts(cur => cur.map(ctx => {
                    return { ...ctx, selected: id === ctx.id };
                }));
            }
        }} appInfo={args.appInfo || {
            href: args.href || 'https://www.pega.com/',
            imageSrc: args.imageSrc || './pega_logo_vertical_white.svg',
            fullImageSrc: args.fullImageSrc ||
                'https://www.pega.com/themes/custom/pegawww_theme/images/pega-logo.svg',
            appName: activeAppName,
            portalName: args.portalName || 'Scrum',
            appNameHidden: args.appNameHidden
        }} searchInput={showSearch
            ? {
                onSearchChange: (value) => {
                    onSearch(value);
                },
                value: searchVal,
                searchResults: results,
                recentSearches,
                loading: searchLoading,
                filters: ['Story', 'Bug'],
                advancedSearchLink: { href: '/' }
            }
            : undefined} appHeader={args.appHeader} searchPage={args.searchPage} caseTypes={args.casesTypesEmpty ? [] : args.createLinks || defaultCreateLinks} links={linksWithHandlers} main={args.main || defaultMainContent} progress={args.progress || progress} cases={args.showCases ? defaultCases : args.cases} banners={args.banners} operator={operatorData} utils={args.utils || defaultUtils} collapsedHoverMenus={args.collapsedHoverMenus}/>);
};
AppShellDemo.args = {
    appName: 'UI Audit',
    appNameHidden: false,
    portalName: 'Scrum',
    href: 'https://www.pega.com/',
    imageSrc: './pega_logo_vertical_white.svg',
    fullImageSrc: 'https://www.pega.com/themes/custom/pegawww_theme/images/pega-logo.svg',
    withSearch: true,
    appHeader: true,
    progress: false,
    notificationsEmpty: false,
    notificationsLoading: false,
    casesTypesEmpty: false,
    recentsEmpty: false,
    recentsLoading: false,
    pinsLoading: false,
    showCases: false
};
AppShellDemo.argTypes = {
    appName: { control: { type: 'text' } },
    appNameHidden: { control: { type: 'boolean' } },
    portalName: { control: { type: 'text' } },
    href: { control: { type: 'text' } },
    imageSrc: { control: { type: 'text' } },
    fullImageSrc: { control: { type: 'text' } },
    withSearch: { control: { type: 'boolean' } },
    appHeader: { control: { type: 'boolean' } },
    progress: { control: { type: 'boolean' } },
    notificationsEmpty: { control: { type: 'boolean' } },
    notificationsLoading: { control: { type: 'boolean' } },
    casesTypesEmpty: { control: { type: 'boolean' } },
    recentsEmpty: { control: { type: 'boolean' } },
    recentsLoading: { control: { type: 'boolean' } },
    pinsLoading: { control: { type: 'boolean' } },
    showCases: { control: { type: 'boolean' } }
};
export const ConfigurableAppShell = (args) => {
    return (<ThemeOverride theme={{
            components: {
                'app-shell': {
                    nav: {
                        'background-color': args.navColor
                    },
                    header: {
                        'background-color': args.headerColor
                    }
                }
            }
        }}>
      <AppShellDemo appHeader/>
    </ThemeOverride>);
};
ConfigurableAppShell.args = {
    navColor: '#252c32',
    headerColor: '#e2f1ff'
};
ConfigurableAppShell.argTypes = {
    navColor: { control: { type: 'color' } },
    headerColor: { control: { type: 'color' } }
};
//# sourceMappingURL=AppShell.stories.jsx.map