import { action } from '@storybook/addon-actions';
import { useState, useRef, useCallback, useEffect, useMemo } from 'react';
import { createUID, DateTimeDisplay, Lightbox, OneColumnPage } from '@pega/cosmos-react-core';
import { AutopilotConfig, Feed, MentionButtonConfig, HashtagButtonConfig, AutopilotGlimpse } from '@pega/cosmos-react-social';
import { Glimpse } from '@pega/cosmos-react-work';
import { AppShellDemo } from '../../core/AppShell/AppShell.stories';
import { FeedPostDemo } from './FeedPost.mocks';
import { FeedNewPostDemo } from './FeedNewPost.mocks';
import { caseMentions, FeedDemoContext, initialFeedPosts, getAttachment, userMentions } from './Feed.mocks';
import { FeedReplyDemo } from './FeedReply.mocks';
import { LogActivityPostContent } from './LogActivityPostType.mocks';
export default {
    title: 'Social/Feed',
    component: Feed,
    args: {
        showPostTypes: true,
        visibilityMode: 'public',
        enableInlineSearch: true,
        simulateServerLatency: false,
        simulateServerError: false
    },
    argTypes: {
        showPostTypes: { control: { type: 'boolean' } },
        visibilityMode: {
            control: { type: 'select' },
            options: ['public', 'private', 'selectable']
        },
        enableInlineSearch: { control: { type: 'boolean' } },
        simulateServerLatency: { control: { type: 'boolean' } },
        simulateServerError: { control: { type: 'boolean' } }
    }
};
export const FeedDemo = (args) => {
    const [posts, setPosts] = useState(initialFeedPosts);
    const [postGenerated, setPostGenerated] = useState(false);
    const [searchResults, setSearchResults] = useState([]);
    const [filters, setFilters] = useState(Array.from({ length: 10 }, (_, index) => {
        return {
            id: `filter-${index + 1}`,
            label: `Filter ${index + 1}`
        };
    }));
    const toggleFilter = (filterId) => {
        const updatedFilters = [...filters];
        const filterToUpdate = updatedFilters.find(x => x.id === filterId);
        if (filterToUpdate)
            filterToUpdate.on = !filterToUpdate.on;
        setFilters(updatedFilters);
    };
    const onSearch = ({ type, search, mentionType }) => {
        if (type === 'mention') {
            const availableMentions = mentionType === 'case' ? caseMentions : userMentions;
            const mentions = availableMentions
                .filter(user => {
                const names = user.primary.toLowerCase().split(' ');
                const searchWords = search.toLowerCase().split(' ');
                return !!searchWords.every((word) => names.find((name) => name.startsWith(word)));
            })
                .map(({ id, primary, secondary, visual, href }) => {
                return {
                    id,
                    primary,
                    secondary: secondary !== undefined && !Array.isArray(secondary) ? [secondary] : secondary,
                    visual,
                    href
                };
            });
            setSearchResults(mentions);
        }
        else {
            setSearchResults(['cosmos', 'hashtag', 'pega']
                .filter(tag => {
                return tag.toLowerCase().includes(search.toLowerCase());
            })
                .map(tag => ({ id: tag, primary: tag })));
        }
    };
    const [loading, setLoading] = useState(false);
    let timeoutId;
    const generateNewPost = useCallback(() => {
        if (!loading && !postGenerated) {
            setLoading(true);
            timeoutId = setTimeout(() => {
                setLoading(false);
                setPostGenerated(true);
                setPosts(oldPosts => [
                    ...oldPosts,
                    {
                        id: createUID(),
                        fullname: 'Feed Bot',
                        icon: 'robot-solid',
                        username: 'feed_bot',
                        content: 'This post was loaded after the Feed was scrolled to the bottom!',
                        attachments: [],
                        replies: []
                    }
                ]);
            }, 1000);
        }
    }, [loading, postGenerated]);
    useEffect(() => {
        return () => clearTimeout(timeoutId);
    }, []);
    const onAutopilotClick = ({ target, onDismiss }) => {
        if (target && onDismiss) {
            return <AutopilotGlimpse target={target} onDismiss={onDismiss} placement='right'/>;
        }
    };
    const onMentionClick = ({ id, type, target, closeGlimpse }) => {
        if (type === 'user') {
            const user = userMentions.find(mention => mention.id === id);
            if (user && target && closeGlimpse) {
                const { primary, secondary, visual, ...restUser } = user;
                return (<Glimpse {...restUser} heading={{
                        primary,
                        secondary: Array.isArray(secondary) ? secondary.join(', ') : secondary,
                        visual
                    }} target={target} onDismiss={() => {
                        closeGlimpse();
                    }} placement='right'/>);
            }
        }
    };
    const [showLightbox, setShowLightbox] = useState(false);
    const [lightboxItems, setLightboxItems] = useState([]);
    const defaultLBIndex = useRef(0);
    const mockAPIItems = useRef([]);
    const getLightboxItems = async (id) => {
        const fileURL = await getAttachment(id);
        const mockItem = mockAPIItems.current.find(item => item.id === id);
        if (mockItem) {
            mockItem.resolved = true;
            mockItem.src = fileURL;
        }
        return mockItem;
    };
    const renderLightbox = (lightboxAttachments, name) => {
        const idx = lightboxAttachments.findIndex(item => item.name === name);
        defaultLBIndex.current = idx > -1 ? idx : 0;
        const items = lightboxAttachments.map(item => {
            const mockItems = mockAPIItems.current.find(mockItem => mockItem.name === item.name);
            if (mockItems?.resolved)
                return mockItems;
            return {
                id: item.id,
                name: item.name,
                format: item.name.split('.').pop(),
                description: '',
                src: null
            };
        });
        setLightboxItems(items);
        setShowLightbox(true);
    };
    const deletePost = (index) => {
        setPosts(oldPosts => {
            const postsCopy = [...oldPosts];
            postsCopy.splice(index, 1);
            return [...postsCopy];
        });
    };
    return (<FeedDemoContext.Provider value={useMemo(() => ({
            posts,
            setPosts,
            showPostTypes: args.showPostTypes,
            visibilityMode: args.visibilityMode,
            simulateServerLatency: args.simulateServerLatency,
            simulateServerError: args.simulateServerError
        }), [
            posts,
            setPosts,
            args.showPostTypes,
            args.visibilityMode,
            args.simulateServerLatency,
            args.simulateServerError
        ])}>
      <Feed title='Pulse' userInfo={{ username: 'demo_user', fullname: 'Demo User', userStatus: 'active' }} searchTypes={[
            { id: 'user', label: 'User' },
            { id: 'case', label: 'Case' },
            { id: 'autopilot', label: 'Autopilot' }
        ]} onDecoratorSearch={args.enableInlineSearch ? onSearch : undefined} searchResults={searchResults} autopilotInfo={{
            id: 'autopilot',
            label: 'Autopilot',
            meta: 'Pega GenAI™ virtual assistant',
            description: 'Mention Autopilot to effortlessly initiate tasks and prompt interactions.\n\nAsk about performance metrics or make a variety of requests using everyday language, and receive a swift response within seconds.'
        }} onAutopilotClick={onAutopilotClick} onMentionClick={onMentionClick} onMentionPreview={args.onMentionPreview} markdownMap={args.markdownMap} interactionRenderers={[MentionButtonConfig, HashtagButtonConfig, AutopilotConfig]} filters={filters} onFilterChange={toggleFilter} loadingPosts={loading} onLoadMore={generateNewPost} newPostRegion={<FeedNewPostDemo onSubmit={postEvent => {
                const { value, attachments, postType, recipients, clear } = postEvent;
                mockAPIItems.current = [
                    ...mockAPIItems.current,
                    ...attachments.map(({ id, name, format, thumbnail }) => {
                        return {
                            id,
                            name,
                            format,
                            description: name,
                            src: thumbnail !== undefined ? thumbnail : null,
                            metadata: [format, <DateTimeDisplay value={new Date()} variant='date'/>],
                            resolved: false
                        };
                    })
                ];
                const newAttachments = attachments.map(fileItem => {
                    const newFile = {
                        ...fileItem,
                        onPreview: () => renderLightbox(attachments, fileItem.name),
                        onDownload: () => action('on download'),
                        onEdit: () => action('on edit')
                    };
                    delete newFile.onDelete;
                    return newFile;
                });
                if (value || newAttachments.length > 0) {
                    const replies = [];
                    const triggersAutopilot = value.match(AutopilotConfig.regexPattern);
                    if (triggersAutopilot && triggersAutopilot.length && triggersAutopilot.length > 0) {
                        replies.push(<FeedReplyDemo key={`autopilot-${createUID()}`} fullname='Autopilot' username='autopilot' content='This is just an automatic reply. In order to truly experience the power of the Pega GenAI™ virtual assistant, make sure to interact with Autopilot in a production environment!' postTimestamp={new Date()}/>);
                    }
                    setPosts(oldPosts => [
                        {
                            id: createUID(),
                            fullname: 'Demo User',
                            username: 'demo_user',
                            userStatus: 'active',
                            content: value,
                            attachments: newAttachments,
                            postType,
                            recipients,
                            visibility: recipients?.length ? 'private' : 'public',
                            replies,
                            postTimestamp: new Date()
                        },
                        ...oldPosts
                    ]);
                    clear();
                }
            }} onLogActivitySubmit={postEvent => {
                const { postType, recipients, activityType, followUpDate, files, comments } = postEvent;
                const replies = [];
                const triggersAutopilot = comments?.match(AutopilotConfig.regexPattern);
                if (triggersAutopilot && triggersAutopilot.length && triggersAutopilot.length > 0) {
                    replies.push(<FeedReplyDemo key={`autopilot-${createUID()}`} fullname='Autopilot' username='autopilot' content='This is just an automatic reply. In order to truly experience the power of the Pega GenAI™ virtual assistant, make sure to interact with Autopilot in a production environment!' postTimestamp={new Date()}/>);
                }
                setPosts(oldPosts => [
                    {
                        id: createUID(),
                        fullname: 'Demo User',
                        username: 'demo_user',
                        userStatus: 'active',
                        content: {
                            activityType,
                            followUpDate,
                            files,
                            comments
                        },
                        recipients,
                        visibility: recipients?.length ? 'private' : 'public',
                        postType,
                        replies,
                        postTimestamp: new Date()
                    },
                    ...oldPosts
                ]);
            }}/>} posts={posts.map((post, i) => {
            let content = post.content;
            if (post.postType?.id === 'log') {
                const { activityType, followUpDate, files, comments } = post.content;
                content = (<LogActivityPostContent activityType={activityType} followUpDate={followUpDate} files={files} comments={comments}/>);
            }
            return (<FeedPostDemo {...post} content={content} key={post.id} onDelete={() => deletePost(i)}/>);
        })}/>
      {showLightbox && (<Lightbox items={lightboxItems} defaultIndex={defaultLBIndex.current} cycle onNavigate={async (id, index) => {
                if (!lightboxItems[index].src) {
                    const updatedImages = [...lightboxItems];
                    const requestedImage = await getLightboxItems(id);
                    if (requestedImage) {
                        updatedImages[index] = requestedImage;
                        setLightboxItems(updatedImages);
                    }
                }
            }} onAfterClose={() => {
                setShowLightbox(false);
                setLightboxItems([]);
            }}/>)}
    </FeedDemoContext.Provider>);
};
export const FeedWithAppShell = (args) => {
    return (<AppShellDemo appHeader main={<OneColumnPage title='Welcome' a={<FeedDemo showPostTypes={args.showPostTypes} visibilityMode={args.visibilityMode} enableInlineSearch={args.enableInlineSearch} simulateServerLatency={args.simulateServerLatency} simulateServerError={args.simulateServerError}/>}/>}/>);
};
FeedWithAppShell.parameters = {
    layout: 'fullscreen'
};
//# sourceMappingURL=Feed.stories.jsx.map