import { useState, useRef, useCallback, useEffect, createRef } from 'react';
import { action } from '@storybook/addon-actions';
import { Card, CardContent, createUID, MenuButton, Icon, registerIcon, Flex, Button, menuHelpers, CardHeader, Text, SummaryList, Grid, FieldValueList, StyledLabel, Modal, useModalManager, useModalContext, useToaster, Banner, Lightbox, createStringMatcher } from '@pega/cosmos-react-core';
import * as filterIcon from '@pega/cosmos-react-core/lib/components/Icon/icons/filter.icon';
import { Email as EmailComponent, EmailConversation, EmailComposer, EmailShell, EmailSummaryItem, EmailSummaryList, EntityList, EmailManager, EmailCaseView } from '@pega/cosmos-react-social';
import { mockData } from '../../core/Lightbox/Lightbox.mocks';
import { AppShellDemo } from '../../core/AppShell/AppShell.stories';
import { bccParticipants, ccParticipants, emailBodyContent, participants, toParticipants, EntityListMockData, viewAnalysisEmailHeaderMock, topicListMock, generateEmailConversationParticipants, templates, handleExternalEntry, emailDemoActions, LaunchAction, baseComposerProps, sentiment, emailSummaryItems, mockEmails, mockSuggestedReplies, getCompositeId, emptyFieldErrorMessage, fieldValidation, emailWorklistItemsMock, contextMenuItemsMock, highlightedEntitiesMock, mockUploadImage, mailDeliverySystemEmail, supportTeamEmail, bodyData, emailAccounts, getTemplate, fetchMockHistory } from './Email.mocks';
import { StyledEmailCardContent } from './Email.styles';
registerIcon(filterIcon);
export default {
    title: 'Social/Email',
    component: EmailComponent
};
export const Email = (args) => {
    const contextMenuHandle = useRef(null);
    const timeout = useRef(null);
    const [trailLoading, setTrailLoading] = useState(false);
    const [trailContent, setTrailContent] = useState();
    const [trailExpanded, setTrailExpanded] = useState(false);
    const [openLightBox, setOpenLightBox] = useState(false);
    const defaultLBIndex = useRef(0);
    const lightBoxItems = mockData.slice(0, 6);
    const handleRightClick = (id, e) => {
        action('onContextMenu')(id, e);
        if (contextMenuHandle.current && args.enableContextMenu) {
            const { setItems, setOpen, setLoading } = contextMenuHandle.current;
            e.preventDefault();
            setLoading(true);
            setItems([]);
            setOpen(true);
            if (timeout.current) {
                clearTimeout(timeout.current);
            }
            timeout.current = window.setTimeout(() => {
                setItems(contextMenuItemsMock);
                setLoading(false);
            }, 1000);
        }
    };
    const onExpandCollapse = async (id) => {
        setTrailExpanded(prev => !prev);
        if (!trailContent) {
            setTrailLoading(true);
            const content = await fetchMockHistory(id);
            setTrailContent(args.trailContent?.length ? args.trailContent : content);
            setTrailLoading(false);
        }
    };
    useEffect(() => {
        return () => {
            if (timeout.current) {
                window.clearTimeout(timeout.current);
            }
        };
    }, []);
    return (<Card>
      <StyledEmailCardContent>
        <EmailComponent id={args.id ?? createUID()} timeStamp='2021-01-05T09:12' from={mockEmails['Laura Stevens']} cc={[mockEmails['Adam Gillchrist'], mockEmails['John Paul']]} bcc={[mockEmails['Anton, Randy'], mockEmails['Hugh Phillips']]} to={[mockEmails['Sara Davis'], mockEmails['John Brown'], mockEmails['Joe Stevens']]} body={args.body ||
            '<div style="font-size: 0.95em;">Hi,<p>I am one of the customer of Indian Overseas Bank, <b><i>Nagercoil</i></b> branch, with code <b><a href="https://www.pega.com" target="_blank"><i>3967</i></a></b>. I have a saving bank account here. My account number is <i>6785420965476</i> with an account balance of ₹97,398.57.</p><p>I have been given a debit cum ATM card from this bank and the same has been lost when I was traveling from Nagercoil to Trichy by Bus on Jan 04, 2021. I remember that my ATM card number was 1920 6746 8653 1256.</p><p>I hereby request you to block my debit card immediately to prevent misuse of the same by some others. Also I request you to send me an new debit card to my address, 22-6-14/A(99M5+RR), Gandhi Road, Hyderabad,  as early as possible. Please call me on +918989812345 if you need more info.<p><br/><p style="font-weight: bold; color: #0fa4ad">Regards,<br/>Laura Stevens</p><img style="width: 100px; margin-left: -8px;" loading="lazy" alt="Pega logo" src="https://www.pega.com/sites/default/files/media/images/2021-10/pega-logo-vertical-positive-rgb-01.png" /></div>'} trail={args.trail ?? {
            expanded: trailExpanded,
            loading: trailLoading,
            onExpandCollapse,
            ...(!trailLoading ? { content: trailContent } : undefined)
        }} entityHighlightMapping={args.enableEntityHighlighting
            ? args.entityHighlightMapping || highlightedEntitiesMock
            : undefined} subject={args.subject || 'I lost my debit card'} banner={args.showEmailBanner
            ? {
                messages: [
                    {
                        label: 'Address not found.',
                        description: '550 5.1.1 The email account that you tried to reach does not exist. Please try double-checking the recipients email address for typos or unnecessary spaces. Learn more at https://support.google.com/mail/?p=NoSuchUser k24-20020aa790d8000000b0050dd7e3b84csor451330pfk.28'
                    }
                ]
            }
            : undefined} onReply={args.onReply || (args.showDraft ? undefined : action('On reply'))} onReplyAll={args.onReplyAll || (args.showDraft ? undefined : action('On reply all'))} onForward={args.onForward || (args.showDraft ? undefined : action('On forward'))} onEditDraft={args.onEditDraft || (args.showDraft ? action('On forward') : undefined)} onDeleteDraft={args.onDeleteDraft || (args.showDraft ? action('On forward') : undefined)} onSuggestionClick={args.onSuggestionClick || action('On Suggested reply clicked')} sentiment={{
            variant: 'neutral'
        }} status={args.showDraft ? 'draft' : undefined} suggestions={mockSuggestedReplies} contextMenu={args.contextMenu ||
            (args.enableContextMenu
                ? {
                    onItemClick: (selectedValue) => {
                        action('onItemClick')(selectedValue);
                        contextMenuHandle.current?.setOpen(false);
                    },
                    onContextMenu: handleRightClick,
                    handle: contextMenuHandle
                }
                : undefined)} attachments={lightBoxItems.map((item, index) => {
            return {
                id: item.id,
                value: item.format,
                displayText: item.name,
                onDownload: action('On Download'),
                onPreview: () => {
                    defaultLBIndex.current = index;
                    setOpenLightBox(true);
                }
            };
        })}/>
        {openLightBox && (<Lightbox items={lightBoxItems} defaultIndex={defaultLBIndex.current} cycle onAfterClose={() => {
                setOpenLightBox(false);
            }} onItemDownload={() => { }}/>)}
      </StyledEmailCardContent>
    </Card>);
};
Email.args = {
    enableEntityHighlighting: false,
    enableContextMenu: false,
    trailContent: undefined,
    showEmailBanner: false,
    showDraft: false
};
Email.argTypes = {
    enableEntityHighlighting: { control: { type: 'boolean' } },
    enableContextMenu: { control: { type: 'boolean' } },
    trailContent: { control: { type: 'text' } },
    showEmailBanner: { control: { type: 'boolean' } },
    showDraft: { control: { type: 'boolean' } }
};
export const Composer = (args) => {
    const pageSize = 4;
    const enableSaveAsDraft = args.enableSaveAsDraft !== undefined ? args.enableSaveAsDraft : true;
    const enableResponseTypeToggle = args.enableResponseTypeToggle !== undefined ? args.enableResponseTypeToggle : true;
    const [composerProgress, setComposerProgress] = useState(false);
    const [open, setOpen] = useState(false);
    const [lightBoxItems, setLightBoxItems] = useState([]);
    const [emailParticipants, setEmailParticipants] = useState(participants.slice(0, 10));
    const composerHandle = useRef(null);
    const defaultLBIndex = useRef(0);
    const [data, setData] = useState({
        to: { value: toParticipants },
        cc: { value: [] },
        bcc: { value: [] },
        subject: { value: 'Request: Pause service' },
        bodyContent: {
            defaultValue: bodyData
        },
        responseType: 'reply',
        selectedTemplateId: '',
        attachments: [],
        bodyContentCurrentValue: ''
    });
    const handleLoadMore = (field, filteredParticipants, showLoadMore) => {
        if (showLoadMore && !data[field]?.loading) {
            setData(prev => {
                return {
                    ...prev,
                    [field]: {
                        ...prev[field],
                        loading: true
                    }
                };
            });
            setTimeout(() => {
                setData(prev => {
                    return {
                        ...prev,
                        [field]: {
                            ...prev[field],
                            loading: false
                        }
                    };
                });
                setEmailParticipants(prev => {
                    const newItems = filteredParticipants.slice(prev.length, prev.length + pageSize);
                    return prev.concat(newItems);
                });
            }, 2000);
        }
    };
    const handleFilterOrLoad = (field, filterValue, loadMore) => {
        let filteredParticipants = [];
        if (['to', 'cc', 'bcc'].includes(field)) {
            if (!filterValue) {
                filteredParticipants = participants;
            }
            else {
                const filterRegex = createStringMatcher(filterValue, 'contains');
                const filteredItems = participants.filter(({ emailAddress, fullName, shortName }) => {
                    return (filterRegex.test(emailAddress) ||
                        filterRegex.test(fullName) ||
                        filterRegex.test(shortName));
                });
                filteredParticipants = filteredItems;
            }
            if (loadMore) {
                handleLoadMore(field, filteredParticipants, emailParticipants.length < filteredParticipants.length);
            }
            else {
                setEmailParticipants(filteredParticipants.slice(0, 10));
            }
        }
    };
    const handleOnChange = (field, value, isProgramatic) => {
        if (field === 'bodyContent') {
            setData(prev => ({
                ...prev,
                bodyContentCurrentValue: value,
                bodyContent: {
                    defaultValue: value
                }
            }));
        }
        if (['responseType', 'selectedTemplateId'].includes(field)) {
            setData(prev => ({
                ...prev,
                [field]: value
            }));
        }
        else if (field === 'attachments') {
            const attachments = value?.map((item, index) => {
                return {
                    ...item,
                    onPreview: () => {
                        defaultLBIndex.current = index;
                        setOpen(true);
                    }
                };
            });
            const lightBox = value?.map(item => {
                const arr = item.name.split('.');
                return {
                    id: item.id,
                    name: item.name,
                    format: arr[arr.length - 1],
                    src: item.File ? window.URL.createObjectURL(item.File) : null
                };
            });
            setLightBoxItems(lightBox);
            setData(prev => ({
                ...prev,
                [field]: attachments
            }));
        }
        else {
            setData(prev => {
                return {
                    ...prev,
                    [field]: { error: undefined, value }
                };
            });
        }
        action('onChange')(field, value, isProgramatic);
    };
    useEffect(() => {
        if (data.responseType === 'reply') {
            setData(prev => {
                return {
                    ...prev,
                    to: {
                        ...prev.to,
                        value: [toParticipants[0]]
                    },
                    cc: {
                        ...prev.cc,
                        value: []
                    },
                    bcc: {
                        ...prev.bcc,
                        value: []
                    }
                };
            });
        }
        else if (data.responseType === 'replyAll') {
            setData(prev => {
                return {
                    ...prev,
                    to: {
                        ...prev.to,
                        value: toParticipants
                    },
                    cc: {
                        ...prev.cc,
                        value: ccParticipants
                    },
                    bcc: {
                        ...prev.bcc,
                        value: bccParticipants
                    }
                };
            });
        }
        else if (data.responseType === 'forward') {
            setData(prev => {
                return {
                    ...prev,
                    to: {
                        ...prev.to,
                        value: []
                    },
                    cc: {
                        ...prev.cc,
                        value: []
                    },
                    bcc: {
                        ...prev.bcc,
                        value: []
                    }
                };
            });
        }
    }, [data.responseType]);
    const onTemplateChange = (templateId) => {
        const selectedTemplate = getTemplate(templateId);
        setComposerProgress({ message: 'Loading template...' });
        setTimeout(() => {
            setComposerProgress(false);
            composerHandle.current?.replaceBodyContent(selectedTemplate?.content || '');
            composerHandle.current?.setCursorLocationToStart?.();
        }, 1000);
    };
    useEffect(() => {
        if (data.selectedTemplateId)
            onTemplateChange(data.selectedTemplateId);
    }, [data.selectedTemplateId]);
    const handleOnSend = () => {
        setData(prev => {
            return {
                ...prev,
                to: {
                    value: prev.to?.value || [],
                    error: data?.to?.value.length === 0 ? emptyFieldErrorMessage : fieldValidation(data?.to?.value)
                },
                cc: {
                    value: prev.cc?.value || [],
                    error: data.cc === undefined ? undefined : fieldValidation(data.cc.value)
                },
                bcc: {
                    value: prev.bcc?.value || [],
                    error: data.bcc === undefined ? undefined : fieldValidation(data.bcc.value)
                },
                subject: {
                    ...prev.subject,
                    error: data.subject?.value === '' ? emptyFieldErrorMessage : undefined
                },
                bodyContent: {
                    ...prev.bodyContent,
                    error: data.bodyContentCurrentValue === '' ? emptyFieldErrorMessage : undefined
                }
            };
        });
    };
    const onImageAdded = (image, id) => {
        action('On Image added');
        setComposerProgress({ message: 'Uploading image' });
        mockUploadImage(image)
            .then(({ src, alt }) => {
            composerHandle.current?.updateImage({ src, alt }, id);
            setComposerProgress(false);
        })
            .catch(() => {
            setComposerProgress(false);
        });
    };
    const pushContentToBody = () => {
        if (args.bodyContentToReplace)
            composerHandle.current?.replaceBodyContent(args.bodyContentToReplace);
    };
    const onEditorInit = () => {
        action('onEditorInit')();
    };
    return (<>
      <EmailComposer handle={composerHandle} progress={composerProgress} onSave={args.onSave || (enableSaveAsDraft ? action('On save') : undefined)} onSend={args.onSend || handleOnSend} onCancel={args.onCancel || action('On cancel')} externalValidator={handleExternalEntry} participants={emailParticipants} onFilterChange={(field, filterValue) => {
            handleFilterOrLoad(field, filterValue, false);
        }} onLoadMore={(field, filterValue) => {
            handleFilterOrLoad(field, filterValue, true);
        }} onChange={args.onChange || handleOnChange} data={args.data || {
            ...data,
            responseType: enableResponseTypeToggle ? data.responseType : undefined
        }} templates={templates} onImageAdded={onImageAdded} onEditorInit={onEditorInit}/>
      <Button onClick={pushContentToBody}>Replace body content</Button>
      {open && (<Lightbox items={lightBoxItems} defaultIndex={defaultLBIndex.current} cycle onAfterClose={() => {
                setOpen(false);
            }} onItemDownload={() => { }}/>)}
    </>);
};
Composer.args = {
    enableResponseTypeToggle: true,
    enableSaveAsDraft: true,
    bodyContentToReplace: 'Hello Eula,<br>Welcome to the world of <b>Awesome product</b>.<br><br>We appreciate your interest in this our <i>Awesome product</i>.<br><br>Please carefully read through the <a href="pega.com">user manual</a> carefully before operating this product.<br>For any queries you can always reach out to us through any of the contact details mentioned on <a href="https://www.pega.com/contact-us">our website</a>.<br><br>  Regards,<br>Customer Support<br><span style="font-weight:bold">Awesome Product</span>'
};
Composer.argTypes = {
    enableResponseTypeToggle: {
        control: 'boolean'
    },
    enableSaveAsDraft: {
        control: { type: 'boolean' }
    },
    bodyContentToReplace: {
        control: { type: 'text' }
    }
};
export const OutboundEmail = (args) => {
    const enableResponseTypeToggle = args.enableResponseTypeToggle || true;
    const enableSaveAsDraft = args.enableSaveAsDraft || true;
    const [composerProgress, setComposerProgress] = useState(false);
    const composerHandle = useRef(null);
    const [emailParticipants, setEmailParticipants] = useState(participants);
    const [userEmailAccounts, setUserEmailAccounts] = useState(emailAccounts);
    const [data, setData] = useState({
        to: { value: [] },
        cc: { value: [] },
        bcc: { value: [] },
        subject: { value: '' },
        selectedTemplateId: '',
        bodyContent: {
            defaultValue: bodyData
        },
        bodyContentCurrentValue: ''
    });
    const handleOnChange = (field, value) => {
        if (field === 'bodyContent') {
            setData(prev => ({
                ...prev,
                bodyContentCurrentValue: value
            }));
        }
        else if (['attachments', 'selectedTemplateId'].includes(field)) {
            setData(prev => ({
                ...prev,
                [field]: value
            }));
        }
        else {
            setData(prev => {
                return {
                    ...prev,
                    [field]: { error: undefined, value }
                };
            });
        }
        action('onChange')(field, value);
    };
    const handleFilterChange = (field, filterValue) => {
        if (['to', 'cc', 'bcc', 'emailAccount'].includes(field)) {
            if (filterValue === '') {
                if (field === 'emailAccount') {
                    setUserEmailAccounts(emailAccounts);
                }
                else
                    setEmailParticipants(participants);
            }
            else {
                const filterRegex = createStringMatcher(filterValue, 'contains');
                const items = field === 'emailAccount' ? emailAccounts : participants;
                const filteredItems = items.filter(({ emailAddress, fullName, shortName }) => {
                    return (filterRegex.test(emailAddress) ||
                        filterRegex.test(fullName) ||
                        filterRegex.test(shortName));
                });
                if (field === 'emailAccount')
                    setUserEmailAccounts(filteredItems);
                else
                    setEmailParticipants(filteredItems);
            }
        }
    };
    const onTemplateChange = (templateId) => {
        const selectedTemplate = getTemplate(templateId);
        setComposerProgress({ message: 'Loading template...' });
        setTimeout(() => {
            setComposerProgress(false);
            composerHandle.current?.replaceBodyContent(selectedTemplate?.content || '');
            composerHandle.current?.setCursorLocationToStart?.();
        }, 1000);
    };
    useEffect(() => {
        if (data.selectedTemplateId)
            onTemplateChange(data.selectedTemplateId);
    }, [data.selectedTemplateId]);
    const handleOnSend = () => {
        setData(prev => {
            return {
                ...prev,
                emailAccount: {
                    value: prev.emailAccount?.value || '',
                    error: data.emailAccount?.value ? undefined : emptyFieldErrorMessage
                },
                to: {
                    value: prev.to?.value || [],
                    error: data?.to?.value.length === 0 ? emptyFieldErrorMessage : fieldValidation(data?.to?.value)
                },
                cc: {
                    value: prev.cc?.value || [],
                    error: data.cc === undefined ? undefined : fieldValidation(data.cc.value)
                },
                bcc: {
                    value: prev.bcc?.value || [],
                    error: data.bcc === undefined ? undefined : fieldValidation(data.bcc.value)
                },
                subject: {
                    ...prev.subject,
                    error: data.subject?.value === '' ? emptyFieldErrorMessage : undefined
                },
                bodyContent: {
                    ...prev.bodyContent,
                    error: data.bodyContentCurrentValue === '' ? emptyFieldErrorMessage : undefined
                }
            };
        });
    };
    const onImageAdded = (image, id) => {
        action('On Image added');
        setComposerProgress({ message: 'Uploading image' });
        mockUploadImage(image)
            .then(({ src, alt }) => {
            composerHandle.current?.updateImage({ src, alt }, id);
            setComposerProgress(false);
        })
            .catch(() => {
            setComposerProgress(false);
        });
    };
    const onEditorInit = () => {
        action('onEditorInit')();
    };
    return (<EmailComposer handle={composerHandle} progress={composerProgress} onSave={args.onSave || (enableSaveAsDraft ? action('On save') : undefined)} onSend={args.onSend || handleOnSend} onCancel={args.onCancel || action('On cancel')} externalValidator={handleExternalEntry} participants={emailParticipants} senderAccounts={userEmailAccounts} onChange={args.onChange || handleOnChange} onFilterChange={handleFilterChange} data={args.data || {
            ...data,
            responseType: enableResponseTypeToggle ? data.responseType : undefined
        }} templates={templates} onImageAdded={onImageAdded} onEditorInit={onEditorInit}/>);
};
OutboundEmail.args = {
    enableResponseTypeToggle: false,
    enableSaveAsDraft: false
};
OutboundEmail.argTypes = {
    enableResponseTypeToggle: {
        control: 'boolean'
    },
    enableSaveAsDraft: {
        control: { type: 'boolean' }
    }
};
export const Conversation = (args) => {
    const emailArr = [
        {
            id: 'item_0',
            timeStamp: '2021-01-05T09:12',
            from: mockEmails['Laura Stevens'],
            cc: [mockEmails['Adam Gillchrist'], mockEmails['John Paul']],
            bcc: [mockEmails['Anton, Randy'], mockEmails['Hugh Phillips']],
            to: [mockEmails['Sara Davis'], mockEmails['John Brown'], mockEmails['Joe Stevens']],
            body: '<div> Hi, <br /> <br /> <div>Sure.. Here is your E-Ticket !! </div> <br /><br /> Regards, <br /> Laura Stevens </div>',
            unRead: true,
            onReply: action('On reply'),
            onForward: action('On forward'),
            onSuggestionClick: action('On Suggested reply clicked'),
            suggestions: mockSuggestedReplies
        },
        {
            id: 'item_1',
            timeStamp: '2021-01-02T03:12',
            from: mockEmails['Sara Davis'],
            cc: [mockEmails['Adam Gillchrist'], mockEmails['John Paul']],
            bcc: [mockEmails['Anton, Randy'], mockEmails['Hugh Phillips']],
            to: [mockEmails['Laura Stevens'], mockEmails['John Brown'], mockEmails['Joe Stevens']],
            body: '<div> Hi, <br /> <br /> <div>I’m still at the airport, I need help now!! </div> <br /><br /> Regards, <br /> Sara Davis </div>',
            onReply: action('On reply'),
            onForward: action('On forward'),
            onSuggestionClick: action('On Suggested reply clicked')
        }
    ];
    return (<EmailConversation participants={generateEmailConversationParticipants(emailArr)} from={generateEmailConversationParticipants(emailArr, ['from'])[0]} to={generateEmailConversationParticipants(emailArr, ['to'])} id={createUID()} timeStamp={emailArr[0].timeStamp} unReadEmailCount={args.unReadEmailCount !== undefined
            ? args.unReadEmailCount
            : emailArr.filter(item => item.unRead).length} emails={args.emails || emailArr} isForwarded={args.isForwarded || false} isCollapsed={args.isCollapsed || false} undelivered={args.undelivered || false} drafts={args.drafts || false}/>);
};
export const EmailShellDemo = (args) => {
    const { create } = useModalManager();
    const { push } = useToaster();
    const actions = ['Transfer', 'End conversation'].map(name => ({
        primary: name,
        id: name,
        onClick: action(`Clicked ${name}`)
    }));
    const [composersData, setComposersData] = useState({});
    const [conversationEmails, setConversationEmails] = useState([]);
    const handleResponseTypeChange = (uid, responseType) => {
        if (responseType === 'reply') {
            setComposersData(prev => {
                return {
                    ...prev,
                    [uid]: {
                        ...prev[uid],
                        data: {
                            ...prev[uid].data,
                            to: {
                                ...prev[uid].data.to,
                                value: [toParticipants[0]]
                            },
                            cc: {
                                ...prev[uid].data.cc,
                                value: []
                            },
                            bcc: {
                                ...prev[uid].data.bcc,
                                value: []
                            }
                        }
                    }
                };
            });
        }
        else if (responseType === 'replyAll') {
            setComposersData(prev => {
                return {
                    ...prev,
                    [uid]: {
                        ...prev[uid],
                        data: {
                            ...prev[uid].data,
                            to: {
                                ...prev[uid].data.to,
                                value: toParticipants
                            },
                            cc: {
                                ...prev[uid].data.cc,
                                value: ccParticipants
                            },
                            bcc: {
                                ...prev[uid].data.bcc,
                                value: bccParticipants
                            }
                        }
                    }
                };
            });
        }
    };
    const handleTemplateChange = (uid, templateId) => {
        const selectedTemplate = getTemplate(templateId);
        setComposersData(prev => {
            return {
                ...prev,
                [uid]: {
                    ...prev[uid],
                    progress: { message: 'Loading template...' }
                }
            };
        });
        setTimeout(() => {
            setComposersData(prev => {
                return {
                    ...prev,
                    [uid]: {
                        ...prev[uid],
                        progress: false
                    }
                };
            });
            let currentData = {};
            setComposersData(prev => {
                currentData = prev;
                return prev;
            });
            if (currentData) {
                currentData[uid]?.handle?.current?.replaceBodyContent(selectedTemplate?.content || '');
            }
        }, 1000);
    };
    const handleChange = (uid, field, value) => {
        setComposersData(prevData => {
            if (field === 'bodyContent' && typeof value === 'string') {
                return {
                    ...prevData,
                    [uid]: {
                        ...prevData[uid],
                        bodyContentCurrentValue: value
                    }
                };
            }
            return {
                ...prevData,
                [uid]: {
                    ...prevData[uid],
                    data: {
                        ...prevData[uid].data,
                        [field]: ['responseType', 'attachments', 'selectedTemplateId'].includes(field)
                            ? value
                            : {
                                error: undefined,
                                value
                            }
                    }
                }
            };
        });
        if (field === 'responseType' && typeof value === 'string') {
            handleResponseTypeChange(uid, value);
        }
        else if (field === 'selectedTemplateId' && typeof value === 'string') {
            handleTemplateChange(uid, value);
        }
    };
    const handleFilterChange = (uid, field, filterValue) => {
        if (['to', 'cc', 'bcc'].includes(field)) {
            let filteredItems;
            if (!filterValue) {
                filteredItems = participants;
            }
            else {
                const filterRegex = createStringMatcher(filterValue, 'contains');
                filteredItems = participants.filter(({ emailAddress, fullName, shortName }) => {
                    return (filterRegex.test(emailAddress) ||
                        filterRegex.test(fullName) ||
                        filterRegex.test(shortName));
                });
            }
            setComposersData(prevData => {
                return {
                    ...prevData,
                    [uid]: {
                        ...prevData[uid],
                        participants: filteredItems
                    }
                };
            });
        }
    };
    const MyModal = ({ currentID }) => {
        const { dismiss } = useModalContext();
        return (<Modal heading='Discard unsaved changes?' actions={<>
            <Button onClick={dismiss}>Go back</Button>
            <div>
              <Button onClick={() => {
                    dismiss();
                    setComposersData(prev => {
                        return {
                            ...prev,
                            [currentID]: {
                                ...prev[currentID],
                                progress: true
                            }
                        };
                    });
                    setTimeout(() => {
                        setComposersData(prev => {
                            const newComposersData = { ...prev };
                            delete newComposersData[currentID];
                            return newComposersData;
                        });
                        push({ content: 'Draft Saved' });
                    }, 1000);
                }}>
                Save & close
              </Button>
              <Button variant='primary' onClick={() => {
                    dismiss();
                    setComposersData(prev => {
                        const newComposersData = { ...prev };
                        delete newComposersData[currentID];
                        return newComposersData;
                    });
                }}>
                Discard
              </Button>
            </div>
          </>}>
        <Text variant='primary'>
          You have unsaved changes. You can discard them or go back to keep working.
        </Text>
      </Modal>);
    };
    const handleCancel = (uid) => {
        create(MyModal, { currentID: uid }, { alert: true });
    };
    const handleSend = (uid) => {
        action('Send')();
        setComposersData(prev => {
            return {
                ...prev,
                [uid]: {
                    ...prev[uid],
                    progress: true
                }
            };
        });
        setTimeout(() => {
            setComposersData(prev => {
                const newComposersData = { ...prev };
                delete newComposersData[uid];
                return newComposersData;
            });
            push({ content: 'Email Send' });
        }, 1000);
    };
    const handleSave = (uid) => {
        action('Save')();
        setComposersData(prev => {
            return {
                ...prev,
                [uid]: {
                    ...prev[uid],
                    progress: true
                }
            };
        });
        setTimeout(() => {
            setComposersData(prev => {
                const newComposersData = { ...prev };
                delete newComposersData[uid];
                return newComposersData;
            });
            push({ content: 'Draft Saved' });
        }, 1000);
    };
    const createOrActivateComposer = (id, launchAction, composerProps) => {
        const uid = getCompositeId(id, launchAction);
        if (composersData[uid]) {
            composersData[uid].handle?.current?.activate();
        }
        else {
            setComposersData(prev => {
                const composerHandle = createRef();
                return {
                    ...prev,
                    [uid]: {
                        ...composerProps,
                        bodyContentCurrentValue: composerProps.data.bodyContent.defaultValue,
                        handle: composerHandle,
                        onChange: (field, value) => handleChange(uid, field, value),
                        onFilterChange: (field, filterValue) => handleFilterChange(uid, field, filterValue),
                        onCancel: () => handleCancel(uid),
                        onSend: () => handleSend(uid),
                        onSave: () => handleSave(uid)
                    }
                };
            });
        }
    };
    const emailsData = [
        {
            id: 'item0',
            timeStamp: '2021-01-05T09:12',
            from: participants[0],
            to: participants.slice(0, 2),
            body: '<div>Hi, <br /> <br /><div>Your address change request is approved.</div> <br /> <br />Regards, <br />Laura Stevens </div>',
            unRead: true,
            subject: 'Pause service',
            suggestions: args.hideSuggestions ? undefined : mockSuggestedReplies,
            attachments: [
                {
                    id: 'item_1_0',
                    value: 'https://pega.com/media/document.doc',
                    displayText: 'Policy document'
                },
                {
                    id: 'item_1_1',
                    value: 'https://pbs.twimg.com/media/ENNN5PAXkAE-hag.jpg',
                    displayText: 'E-Ticket'
                }
            ].map(attachment => {
                return {
                    ...attachment,
                    onDownload: action('On attachment download')
                };
            })
        },
        {
            id: 'item1',
            timeStamp: '2021-01-02T03:12',
            from: participants[3],
            to: participants.slice(2, 4),
            body: emailBodyContent,
            unRead: true,
            subject: 'Pause service'
        }
    ].map(emailData => {
        const emailActionItems = emailDemoActions(emailData.id, emailData.subject, createOrActivateComposer, false, emailData.body);
        return {
            ...emailData,
            onReply: (id) => {
                createOrActivateComposer(id, LaunchAction.REPLY, {
                    ...baseComposerProps,
                    participants,
                    data: {
                        ...baseComposerProps.data,
                        responseType: 'reply',
                        subject: { value: `Re-${emailData.subject}` || '' }
                    },
                    externalValidator: handleExternalEntry
                });
            },
            onForward: id => {
                createOrActivateComposer(id, LaunchAction.FORWARD, {
                    ...baseComposerProps,
                    participants,
                    data: {
                        ...baseComposerProps.data,
                        responseType: 'forward',
                        subject: { value: `Fw-${emailData.subject}` || '' }
                    },
                    externalValidator: handleExternalEntry
                });
            },
            onSuggestionClick: (id, suggestionId) => {
                const suggestion = emailData.suggestions?.find(item => item.id === suggestionId);
                createOrActivateComposer(id, LaunchAction.SUGGESTION, {
                    ...baseComposerProps,
                    participants,
                    data: {
                        ...baseComposerProps.data,
                        responseType: 'reply',
                        subject: { value: suggestion?.title || '' },
                        bodyContent: { defaultValue: suggestion ? suggestion.content : '' },
                        selectedTemplateId: suggestionId
                    },
                    externalValidator: handleExternalEntry
                });
            },
            actions: emailActionItems,
            tags: args.hideSuggestions
                ? undefined
                : {
                    items: ['Pause service', 'Lost or stolen'],
                    label: 'Associated service cases',
                    onRemove: action('On Associated service case remove'),
                    dismissable: true
                }
        };
    });
    const DeleteDraft = ({ currentID }) => {
        const { dismiss } = useModalContext();
        return (<Modal heading='Delete draft?' actions={<>
            <Button onClick={dismiss}>Go back</Button>

            <Button variant='primary' onClick={() => {
                    dismiss();
                    setConversationEmails(prev => {
                        const newEmailConversation = [];
                        prev.forEach(arr => {
                            const newArr = arr.filter(index => index.id !== currentID);
                            if (newArr.length !== 0)
                                newEmailConversation.push(newArr);
                        });
                        return newEmailConversation;
                    });
                }}>
              Delete
            </Button>
          </>}>
        <Text>Are you sure that you want to permanently delete the selected message?</Text>
      </Modal>);
    };
    const deleteEmail = (id) => {
        create(DeleteDraft, { currentID: id }, { alert: true });
    };
    useEffect(() => {
        setConversationEmails([
            [
                {
                    ...emailsData[1],
                    id: 'item0',
                    from: mailDeliverySystemEmail,
                    to: [supportTeamEmail],
                    body: '<div>Hi, <br /> <br /><div>Your address change request is approved.</div> <br /> <br />Regards, <br />Support team </div>',
                    banner: {
                        messages: [
                            {
                                label: 'Address not found.',
                                description: '550 5.1.1 The email account that you tried to reach does not exist. Please try double-checking the recipients email address for typos or unnecessary spaces. Learn more at https://support.google.com/mail/?p=NoSuchUser k24-20020aa790d8000000b0050dd7e3b84csor451330pfk.28'
                            }
                        ]
                    },
                    onReply: undefined,
                    onForward: undefined
                },
                { ...emailsData[1], unRead: false }
            ],
            [
                {
                    ...emailsData[0],
                    id: 'item2',
                    status: 'draft',
                    onEditDraft: (id) => createOrActivateComposer(id, LaunchAction.REPLY, {
                        ...baseComposerProps,
                        data: {
                            ...baseComposerProps.data,
                            responseType: 'reply',
                            subject: { value: `Re-${emailsData[0].subject}` || '' },
                            bodyContent: { defaultValue: emailsData[0].body || '' }
                        }
                    }),
                    onDeleteDraft: (id) => deleteEmail(id),
                    onReply: undefined,
                    onForward: undefined,
                    suggestions: undefined,
                    unRead: false,
                    timeStamp: '2021-01-03T17:15',
                    from: mockEmails['Hugh Phillips'],
                    to: [mockEmails['Mystery Rey'], ...emailsData[0].to],
                    cc: [mockEmails['Adam Gillchrist']],
                    bcc: [mockEmails['Anton, Randy'], mockEmails['Hugh Phillips']],
                    body: '<div>Hi, <br /> <br /><div>Sure, Our executive will come and check your connection in 24hrs. </div>  <br />Regards, <br />Hugh Phillips </div>'
                },
                {
                    ...emailsData[1],
                    id: 'item3',
                    status: 'draft',
                    onEditDraft: (id) => createOrActivateComposer(id, LaunchAction.REPLY, {
                        ...baseComposerProps,
                        data: {
                            ...baseComposerProps.data,
                            responseType: 'reply',
                            subject: { value: `Re-${emailsData[0].subject}` || '' },
                            bodyContent: { defaultValue: emailsData[0].body || '' }
                        }
                    }),
                    onDeleteDraft: (id) => deleteEmail(id),
                    onReply: undefined,
                    onForward: undefined,
                    suggestions: undefined,
                    unRead: false,
                    timeStamp: '2021-01-02T14:16',
                    from: mockEmails['Mystery Rey'],
                    to: [mockEmails['Hugh Phillips']],
                    body: '<div>Hi, <br /> <br /><div>Can you fix my internet connection. </div> <br /> <br />Regards, <br />Rey Mystery </div>'
                }
            ],
            [
                {
                    ...emailsData[0],
                    id: 'item4',
                    unRead: true,
                    timeStamp: '2020-12-05T18:18',
                    from: mockEmails['Laura Stevens'],
                    to: [mockEmails['Sara Davis']],
                    body: '<div>Hi, <br /> <br /><div>Sure, Our executive will call you shortly. </div> <br /> <br />Regards, <br />Laura Stevens </div>',
                    sentiment: {
                        variant: 'positive'
                    }
                },
                {
                    ...emailsData[1],
                    id: 'item5',
                    unRead: true,
                    timeStamp: '2021-01-04T08:30',
                    from: mockEmails['Sara Davis'],
                    to: [mockEmails['Laura Stevens']],
                    body: '<div>Hi, <br /> <br /><div>Can you show please explain your new mobile plans. </div> <br /> <br />Regards, <br />Sara Davis </div>'
                }
            ]
        ]);
    }, []);
    const emailConversations = conversationEmails.map((emails, i) => {
        return {
            from: i === 0 ? emails[1].from : generateEmailConversationParticipants(emails, ['from'])[0],
            to: i === 0 ? emails[1].to : emails[0].to,
            id: `item_${i}`,
            timeStamp: emails[0].timeStamp,
            unReadEmailCount: emails.filter(item => item.unRead).length,
            emails,
            sentiment: emails[0].sentiment,
            isForwarded: i !== 2,
            isCollapsed: i !== 0,
            drafts: i === 1,
            undelivered: i === 0
        };
    });
    const singleEmailConversation = [
        {
            from: generateEmailConversationParticipants(emailsData, ['from'])[0],
            to: generateEmailConversationParticipants(emailsData, ['to']),
            id: 'item_0',
            timeStamp: new Date(emailsData[0].timeStamp),
            unReadEmailCount: 1,
            emails: [
                {
                    ...emailsData[1],
                    id: 'item0',
                    from: mailDeliverySystemEmail,
                    to: [supportTeamEmail],
                    body: '<div>Hi, <br /> <br /><div>Your address change request is approved.</div> <br /> <br />Regards, <br />Support team </div>',
                    banner: {
                        messages: [
                            {
                                label: 'Address not found.',
                                description: '550 5.1.1 The email account that you tried to reach does not exist. Please try double-checking the recipients email address for typos or unnecessary spaces. Learn more at https://support.google.com/mail/?p=NoSuchUser k24-20020aa790d8000000b0050dd7e3b84csor451330pfk.28'
                            }
                        ]
                    },
                    onReply: undefined,
                    onForward: undefined
                },
                { ...emailsData[1], unRead: false }
            ]
        }
    ];
    return (<>
      <EmailShell headerProps={args.headerProps ||
            (args.showHeader
                ? {
                    actions: (<Flex container={{
                            alignItems: 'center',
                            gap: 0
                        }}>
                    <Button variant='simple' icon label='Filter conversations'>
                      <Icon name='filter'/>
                    </Button>
                    <MenuButton variant='simple' text='More actions' icon='more' iconOnly portal menu={{ items: actions }}/>
                  </Flex>),
                    subject: 'Pause service'
                }
                : undefined)} autoCollapse={args.autoCollapse} conversations={args.conversations ||
            (args.singleConversation ? singleEmailConversation : emailConversations)}/>
      <>
        {Object.keys(composersData).map(guid => {
            return <EmailComposer key={guid} {...composersData[guid]}/>;
        })}
      </>
    </>);
};
EmailShellDemo.args = {
    autoCollapse: true,
    hideSuggestions: false,
    singleConversation: false,
    showHeader: true
};
EmailShellDemo.argTypes = {
    autoCollapse: { control: { type: 'boolean' } },
    hideSuggestions: { control: { type: 'boolean' } },
    singleConversation: { control: { type: 'boolean' } },
    showHeader: { control: { type: 'boolean' } }
};
export const EntityListDemo = (args) => {
    const itemCounter = useRef(3);
    const timeout = useRef(null);
    const contextMenuHandle = useRef(null);
    const headerProps = {
        icon: 'list-number',
        text: 'Entities'
    };
    const handleRightClick = (e) => {
        action('onContextMenu')(e);
        if (contextMenuHandle.current && args.enableContextMenu) {
            itemCounter.current += 1;
            const { setItems, setOpen, setLoading } = contextMenuHandle.current;
            e.preventDefault();
            setLoading(true);
            setItems([]);
            setOpen(true);
            if (timeout.current) {
                window.clearTimeout(timeout.current);
            }
            timeout.current = window.setTimeout(() => {
                setItems(contextMenuItemsMock);
                setLoading(false);
            }, 1000);
        }
    };
    useEffect(() => {
        return () => {
            if (timeout.current) {
                window.clearTimeout(timeout.current);
            }
        };
    }, []);
    return (<EntityList header={headerProps} content={args.content || EntityListMockData} contextMenu={{
            onItemClick: action('onItemClick'),
            onContextMenu: args.onContextMenu || handleRightClick,
            handle: contextMenuHandle
        }}/>);
};
EntityListDemo.args = {
    enableContextMenu: true
};
EntityListDemo.argTypes = {
    enableContextMenu: { control: { type: 'boolean' } }
};
export const EmailSummaryItemDemo = (args) => {
    return (<EmailSummaryItem id={createUID()} activeParticipants={[
            {
                shortName: 'Robert',
                fullName: 'Robert Downer',
                emailAddress: 'robert.downey@example.com'
            },
            {
                shortName: 'Nathan',
                fullName: 'Nathan Swanson',
                emailAddress: 'nathan.swanson@example.com'
            }
        ]} message='I have a quick question on traveling to India. How do I reach Hyderabad?' timeStamp={new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 24))} topic='Missing Luggage' sentiment={sentiment} urgency={10} unreadEmailCount={args.unreadEmailCount} active={args.isActive} onSelect={(id) => {
            action('onSelect')(id);
        }}/>);
};
EmailSummaryItemDemo.args = {
    unreadEmailCount: 0,
    isActive: false
};
EmailSummaryItemDemo.argTypes = {
    unreadEmailCount: { control: { type: 'number' } },
    isActive: { control: { type: 'boolean' } }
};
export const EmailSummaryListDemo = (args) => {
    const INITIAL_CHUNK_SIZE = 9;
    const APPEND_CHUNK_SIZE = 1;
    const [allEmailItems, setAllEmailItems] = useState(args.items || emailSummaryItems.slice(0, INITIAL_CHUNK_SIZE));
    useEffect(() => {
        if (args.items)
            setAllEmailItems(args.items);
    }, [args.items]);
    const [categories, setCategories] = useState(emailWorklistItemsMock);
    const [currentItemId, setCurrentItemId] = useState(emailSummaryItems[0].id);
    const handleItemClick = (id) => {
        const index = allEmailItems.findIndex(emailItem => {
            return emailItem.id === id;
        });
        const newEmailItems = [...allEmailItems];
        newEmailItems.splice(index, 1, { ...allEmailItems[index], unreadEmailCount: 0 });
        setAllEmailItems(newEmailItems);
        setCurrentItemId(id);
    };
    const onCategoryClick = (id) => {
        setCategories(cur => menuHelpers.toggleSelected(cur, id, 'single-select'));
    };
    const [loading, setLoading] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const loadMore = useCallback(() => {
        if (!loading) {
            setLoading(true);
            setTimeout(() => {
                setLoading(false);
                setAllEmailItems(prevItems => {
                    const previousItemsLength = prevItems.length;
                    const newItems = emailSummaryItems.slice(previousItemsLength, previousItemsLength + APPEND_CHUNK_SIZE);
                    if (newItems.length === 0) {
                        setHasMore(false);
                    }
                    return [...prevItems, ...newItems];
                });
            }, 1500);
        }
    }, [loading]);
    return (<EmailSummaryList count={args.count
            ? args.count
            : {
                total: emailSummaryItems.length,
                unread: allEmailItems.reduce((result, email) => email.unreadEmailCount ? result + email.unreadEmailCount : result, 0)
            }} categories={categories} searchQuery={args.searchQuery} items={args.items || allEmailItems} onItemClick={args.onItemClick || handleItemClick} onCategoryClick={onCategoryClick} onLoadMore={args.onLoadMore || (hasMore ? loadMore : undefined)} loading={args.loading || loading} emptyMessage='No emails.' currentItemId={args.currentItemId || currentItemId}/>);
};
EmailSummaryListDemo.args = {
    searchQuery: ''
};
EmailSummaryListDemo.argTypes = {
    searchQuery: { control: { type: 'text' } }
};
export const EmailCaseViewDemo = (args) => {
    const content = <EmailShellDemo />;
    const utilities = (<Grid container={{ rowGap: 2 }}>
      <EntityListDemo />
      <Card>
        <CardHeader container={{ alignItems: 'center', gap: 1 }}>
          <Icon name='document-doc'/>
          <Text variant='h3'>Email header</Text>
        </CardHeader>
        <CardContent>
          <FieldValueList fields={viewAnalysisEmailHeaderMock} variant='stacked'/>
        </CardContent>
      </Card>
      <SummaryList name='Topics' icon='headline' items={topicListMock.map(items => ({
            ...items,
            primary: <StyledLabel>{items.primary}</StyledLabel>,
            secondary: (<Flex container={{ direction: 'row', justify: 'between' }}>
              <Text variant='primary'>{items.secondary.indicator}</Text>
              <StyledLabel>{items.secondary.value}</StyledLabel>
            </Flex>)
        }))} noItemsText='No items'/>
    </Grid>);
    return (<AppShellDemo appHeader main={<EmailCaseView header={args.showHeader
                ? {
                    icon: 'mail',
                    title: 'ET-5432'
                }
                : undefined} banners={args.showBanners && (<Banner variant='urgent' messages={['Your email could not be delivered due to poor network connection.']}/>)} content={content} utilities={!args.noUtilityView && utilities} utilitiesSummaryItems={!args.noUtilityView
                ? [
                    { id: '1', iconName: 'list-number', count: 7, name: 'Entities' },
                    { id: '2', iconName: 'document-doc', count: 1, name: 'Email header' },
                    { id: '3', iconName: 'headline', count: 4, name: 'Topics' }
                ]
                : undefined} defaultUtilitiesExpanded/>}/>);
};
EmailCaseViewDemo.args = {
    showBanners: false,
    noUtilityView: false,
    showHeader: true
};
EmailCaseViewDemo.argTypes = {
    showBanners: { control: { type: 'boolean' } },
    noUtilityView: { control: { type: 'boolean' } },
    showHeader: { control: { type: 'boolean' } }
};
EmailCaseViewDemo.parameters = {
    layout: 'fullscreen'
};
export const EmailManagerAppShell = (args) => {
    const INITIAL_CHUNK_SIZE = 9;
    const APPEND_CHUNK_SIZE = 1;
    const NEXT_EMAIL_ID = 'item_11';
    const [emailList, setEmailList] = useState(emailSummaryItems.slice(0, INITIAL_CHUNK_SIZE));
    const [loading, setLoading] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const [currentItemId, setCurrentItemId] = useState(emailSummaryItems[0].id);
    const [hasBanner, setHasBanner] = useState(false);
    const [appshellProgress, setAppshellProgress] = useState(false);
    const getNextEmailClicked = useRef(false);
    useEffect(() => {
        setHasBanner(args.showAppshellBanner || false);
    }, [args.showAppshellBanner]);
    const handleEmailItemClick = (id) => {
        const index = emailList.findIndex(emailItem => {
            return emailItem.id === id;
        });
        const newEmailList = [...emailList];
        newEmailList.splice(index, 1, { ...emailList[index], unreadEmailCount: 0 });
        setEmailList(newEmailList);
        setCurrentItemId(id);
    };
    const onLoadMore = useCallback(() => {
        if (!loading) {
            setLoading(true);
            setTimeout(() => {
                setLoading(false);
                setEmailList(prevItems => {
                    const previousItemsLength = prevItems.length;
                    const newItems = emailSummaryItems.slice(previousItemsLength, previousItemsLength + APPEND_CHUNK_SIZE);
                    if (newItems.length === 0) {
                        setHasMore(false);
                    }
                    return [...prevItems, ...newItems];
                });
            }, 1500);
        }
    }, [loading]);
    const utilities = (<Grid container={{ rowGap: 2 }}>
      <EntityListDemo />
      <Card>
        <CardHeader container={{ alignItems: 'center', gap: 1 }}>
          <Icon name='document-doc'/>
          <Text variant='h3'>Email header</Text>
        </CardHeader>
        <CardContent>
          <FieldValueList fields={viewAnalysisEmailHeaderMock} variant='stacked'/>
        </CardContent>
      </Card>
      <SummaryList name='Topics' icon='headline' items={topicListMock.map(items => ({
            ...items,
            primary: <StyledLabel>{items.primary}</StyledLabel>,
            secondary: (<Flex container={{ direction: 'row', justify: 'between' }}>
              <Text variant='primary'>{items.secondary.indicator}</Text>
              <StyledLabel>{items.secondary.value}</StyledLabel>
            </Flex>)
        }))} noItemsText='No items'/>
    </Grid>);
    const content = <EmailShellDemo showHeader={false}/>;
    const handleGetNextEmailClick = () => {
        getNextEmailClicked.current = true;
        setCurrentItemId('');
        setAppshellProgress(true);
        setTimeout(() => {
            const nextEmailIndex = emailSummaryItems.findIndex(item => item.id === NEXT_EMAIL_ID);
            setEmailList(emailSummaryItems.slice(0, INITIAL_CHUNK_SIZE > nextEmailIndex ? INITIAL_CHUNK_SIZE : nextEmailIndex + 1));
            setAppshellProgress(false);
        }, 1500);
    };
    useEffect(() => {
        if (getNextEmailClicked.current) {
            setCurrentItemId(NEXT_EMAIL_ID);
            handleEmailItemClick(NEXT_EMAIL_ID);
            getNextEmailClicked.current = false;
        }
    }, [emailList]);
    return (<AppShellDemo appHeader main={<EmailManager header={args.showHeader
                ? {
                    icon: 'mail',
                    title: 'Inbox',
                    getNextEmail: args.showGetNextEmail ? handleGetNextEmailClick : undefined
                }
                : undefined} list={<EmailSummaryListDemo onItemClick={handleEmailItemClick} items={emailList} onLoadMore={hasMore ? onLoadMore : undefined} loading={loading} currentItemId={currentItemId} searchQuery={args.searchQuery}/>} emailCaseDetails={!args.showEmptyView && (<EmailCaseView banners={args.showCaseViewBanners && (<Banner variant='urgent' messages={[
                        'Your email could not be delivered due to poor network connection.'
                    ]}/>)} content={content} utilities={args.showUtilities && utilities} utilitiesSummaryItems={args.showUtilities
                    ? [
                        { id: '1', iconName: 'list-number', count: 7, name: 'Entities' },
                        { id: '2', iconName: 'document-doc', count: 1, name: 'Email header' },
                        { id: '3', iconName: 'headline', count: 4, name: 'Topics' }
                    ]
                    : undefined} defaultUtilitiesExpanded={false}/>)}/>} banners={hasBanner && (<Banner onDismiss={() => setHasBanner(false)} variant='urgent' messages={['Your email could not be fetched due to poor network connection']}/>)} progress={appshellProgress}/>);
};
EmailManagerAppShell.args = {
    showEmptyView: false,
    showHeader: true,
    showCaseViewBanners: false,
    showUtilities: true,
    showAppshellBanner: false,
    showGetNextEmail: false,
    searchQuery: ''
};
EmailManagerAppShell.argTypes = {
    showEmptyView: { control: { type: 'boolean' } },
    showHeader: { control: { type: 'boolean' } },
    showCaseViewBanners: { control: { type: 'boolean' } },
    showUtilities: { control: { type: 'boolean' } },
    showAppshellBanner: { control: { type: 'boolean' } },
    showGetNextEmail: { control: { type: 'boolean' } },
    searchQuery: { control: { type: 'text' } }
};
EmailManagerAppShell.parameters = {
    layout: 'fullscreen'
};
//# sourceMappingURL=Email.stories.jsx.map