import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { action } from '@storybook/addon-actions';
import { Button, Icon, registerIcon, Text, MenuButton, Flex, Popover, Link, createUID, useOuterEvent, Select, Option, useElement, useModalManager, useModalContext, Modal, SummaryItem, useToaster, SearchInput, menuHelpers, VisuallyHiddenText, Menu, useEscape, usePrevious, Lightbox, getKindFromMimeType, getMimeTypeFromFile } from '@pega/cosmos-react-core';
import * as arrowMicroDownIcon from '@pega/cosmos-react-core/lib/components/Icon/icons/arrow-micro-down.icon';
import * as replyIcon from '@pega/cosmos-react-core/lib/components/Icon/icons/reply.icon';
import * as replyAllIcon from '@pega/cosmos-react-core/lib/components/Icon/icons/reply-all.icon';
import * as forwardIcon from '@pega/cosmos-react-core/lib/components/Icon/icons/forward.icon';
import { Chat, ChatHeader, ChatComposer, Message, NewMessageSeparatorId, SuggestedReplyPicker, SystemMessage, TypeIndicator, isReplyErrorState, isReplyLoadingState } from '@pega/cosmos-react-social';
import { mockData } from '../../core/Lightbox/Lightbox.mocks';
import { ChatMockData, phrasesDisplayNames, phrasesMessages, contextItems as contextItemsMock, BotConversation, ClaimsAgentConversation, LiveChatConversation } from './Chat.mocks';
registerIcon(forwardIcon, replyIcon, replyAllIcon, arrowMicroDownIcon);
export default {
    title: 'Social/Chat',
    component: Chat
};
export const ChatHeaderDemo = (args) => {
    const [contextItems, setContextItems] = useState([]);
    const [loading, setLoading] = useState(false);
    return (<ChatHeader title={args.title} icon={args.icon || 'chat'} actions={[
            { id: 'action-1', primary: 'Transfer' },
            { id: 'action-2', primary: 'End chat' }
        ]} sentiment={{
            variant: 'positive',
            'aria-label': 'Sentiment is positive'
        }} customer={args.customer} authenticated={args.authenticated} context={{
            heading: args.contextHeading,
            items: contextItems,
            onClick: () => {
                setLoading(true);
                setTimeout(() => {
                    setContextItems(contextItemsMock);
                    setLoading(false);
                }, 1000);
            },
            loading
        }}/>);
};
ChatHeaderDemo.args = {
    title: 'Live chat',
    icon: 'chat',
    customer: 'Ginger Ventura',
    authenticated: true,
    contextHeading: 'Context data'
};
ChatHeaderDemo.argTypes = {
    title: { control: { type: 'text' } },
    icon: { control: { type: 'text' }, type: { name: 'string', required: false } },
    customer: { control: { type: 'text' } },
    authenticated: { control: { type: 'boolean' }, type: { name: 'string', required: false } },
    contextHeading: { control: { type: 'text' }, type: { name: 'string', required: false } }
};
export const MessageDemo = (args) => {
    const actions = [
        {
            text: 'Associate with case',
            id: 'Associate with case',
            onClick: () => {
                action('Associate with case');
            }
        },
        {
            text: 'Download',
            id: 'Download',
            onClick: () => {
                action('Download');
            }
        }
    ];
    const attachments = [
        {
            id: '2499167340',
            name: 'Location',
            icon: 'document',
            meta: 'PNG 0.1 MB',
            thumbnail: 'https://pegasystems.github.io/uplus-wss/health_provider/img/secondary-options.jpg',
            actions
        },
        {
            id: '2499167341',
            name: 'FAQ with detailed terms and conditions of the policy',
            icon: 'document-pdf',
            meta: 'PDF 0.7 MB',
            actions
        }
    ];
    const mediaPageLinks = [
        {
            id: '2499167349',
            href: 'https://collaborate.pega.com/',
            title: 'Ask the expert'
        }
    ];
    return (<Message attachments={args.showAttachments ? attachments : undefined} mediaPageLinks={args.showMediaPageLinks ? mediaPageLinks : undefined} avatarInfo={args.direction === 'in' && args.senderType !== 'bot'
            ? {
                name: 'John Brown',
                imageSrc: args.showAvatarImage
                    ? 'https://pegasystems.github.io/uplus-wss/insurance/img/option-1.jpg'
                    : undefined
            }
            : undefined} timestamp={args.showTimestamp ? args.timestamp : undefined} status={args.showStatus ? args.status : undefined} message={args.message} direction={args.direction} senderType={args.senderType} senderId={createUID()} agentVariant={args.agentVariant} messageHeader={args.showHeader ? { content: args.headerContent, meta: args.headerMeta } : undefined}/>);
};
MessageDemo.args = {
    direction: 'in',
    senderType: 'customer',
    agentVariant: 0,
    message: 'Hi, Welcome to u-plus. How can I help you?',
    showStatus: true,
    status: 'delivered',
    showTimestamp: true,
    timestamp: '1:44 PM',
    showHeader: false,
    headerContent: 'Public Reply',
    headerMeta: 'I-12345',
    showAvatarImage: false,
    showAttachments: false,
    showMediaPageLinks: false
};
MessageDemo.argTypes = {
    direction: { options: ['in', 'out'], control: { type: 'inline-radio' } },
    senderType: { options: ['agent', 'customer', 'bot'], control: { type: 'inline-radio' } },
    agentVariant: { type: 'number' },
    message: { type: 'string' },
    showTimestamp: { type: 'boolean' },
    timestamp: { control: 'text' },
    showStatus: { type: 'boolean' },
    status: {
        options: ['delivered', 'opened', 'undeliverable', 'sent'],
        control: { type: 'inline-radio' }
    },
    showHeader: { control: 'boolean' },
    headerContent: { control: 'text' },
    headerMeta: { control: 'text' },
    showAvatarImage: { control: 'boolean' },
    showAttachments: { control: 'boolean' },
    showMediaPageLinks: { control: 'boolean' }
};
export const SystemMessageDemo = (args) => (<SystemMessage message={args.message} timestamp={args.timestamp} variant={args.variant}/>);
SystemMessageDemo.args = {
    message: 'John Brown has joined',
    variant: 'secondary',
    timestamp: '10:00 AM'
};
SystemMessageDemo.argTypes = {
    message: { control: { type: 'text' } },
    variant: { options: ['primary', 'secondary'], control: { type: 'select' } },
    timestamp: { control: { type: 'text' } }
};
export const TypeIndicatorDemo = (args) => {
    return (<TypeIndicator avatarInfo={{ name: 'John Brown' }} message={args.message} senderId='johnBrown' senderType='agent'/>);
};
TypeIndicatorDemo.args = {
    message: ''
};
TypeIndicatorDemo.argTypes = {
    message: { control: { type: 'text' } }
};
export const SuggestedReplyPickerDemo = (args) => {
    const [suggestedRepliesCollapsed, setSuggestedRepliesCollapsed] = useState(false);
    const [currentReplyId, setCurrentReplyId] = useState(ChatMockData?.suggestedReplies?.[0]?.id || '');
    const renderReplies = args.singleSuggestedReply
        ? [ChatMockData.suggestedReplies[0]]
        : ChatMockData.suggestedReplies;
    return (<SuggestedReplyPicker replies={args.noSuggestedReplies ? [] : renderReplies} onSelect={suggestedReply => {
            if (!isReplyErrorState(suggestedReply) && !isReplyLoadingState(suggestedReply))
                action(`Suggested reply picked ${suggestedReply.message}`)();
        }} collapsed={suggestedRepliesCollapsed} onExpandCollapse={() => {
            setSuggestedRepliesCollapsed(prev => !prev);
        }} currentReplyId={currentReplyId} onReplyChange={setCurrentReplyId} showNotification={args.showNotification} onSend={() => action('Send suggested reply')} disabled={args.disableButton}/>);
};
SuggestedReplyPickerDemo.args = {
    showNotification: false,
    singleSuggestedReply: false,
    noSuggestedReplies: false,
    disableButton: false
};
SuggestedReplyPickerDemo.argTypes = {
    showNotification: { type: 'boolean' },
    singleSuggestedReply: { type: 'boolean' },
    noSuggestedReplies: { type: 'boolean' },
    disableButton: { type: 'boolean' }
};
export const ChatComposerDemo = (args) => {
    const attachments = mockData.slice(0, 4).map(item => {
        return {
            id: item.id,
            name: item.name,
            format: item.format,
            onDelete: () => { },
            onPreview: () => { }
        };
    });
    const onJoinConversationClick = {
        onClick: () => {
            action('on click of join conversation');
        }
    };
    return (<ChatComposer maxAttachments={args.maxAttachments} attachments={attachments} maxLength={256} placeholder='Type here to send message' onSend={() => { }} onSuggestReplyClick={args.showSuggestReplyButton ? action('Suggest reply clicked') : undefined} joinConversation={args.showJoinConversationButton ? onJoinConversationClick : undefined}>
      <MenuButton text='Phrases' menu={{ items: [] }}/>
      <MenuButton text='Page Push' menu={{ items: [] }}/>
    </ChatComposer>);
};
ChatComposerDemo.args = {
    maxAttachments: 2,
    showSuggestReplyButton: false,
    showJoinConversationButton: false
};
ChatComposerDemo.argTypes = {
    maxAttachments: { control: { type: 'number' } },
    showSuggestReplyButton: { control: { type: 'boolean' } },
    showJoinConversationButton: { control: { type: 'boolean' } }
};
export const StandardChat = (args) => {
    const ChatMockDataClone = useMemo(() => {
        return JSON.parse(JSON.stringify(ChatMockData));
    }, [ChatMockData]);
    const Channels = {
        label: 'Channel',
        options: {
            LiveChat: {
                title: 'Live chat',
                icon: 'chat'
            },
            Twitter: {
                title: 'Twitter chat',
                icon: 'twitter'
            },
            Facebook: {
                title: 'Facebook messenger',
                icon: 'facebook'
            }
        }
    };
    const { chatMessages: mockChatMessagesJson, suggestedReplies } = ChatMockDataClone;
    const { create } = useModalManager();
    const MyModal = () => {
        const { dismiss } = useModalContext();
        const { push } = useToaster();
        return (<Modal heading='Associate with case' actions={<>
            <Button onClick={() => {
                    dismiss();
                    push({ content: 'Cancelled' });
                }}>
              Cancel
            </Button>
            <Button variant='primary' onClick={() => {
                    dismiss();
                    push({ content: 'Successfully Submitted!!' });
                }}>
              Submit
            </Button>
          </>} center>
        <Flex container={{ gap: 2, direction: 'column' }}>
          <SummaryItem primary={<Text variant='secondary'>Security policy</Text>} secondary={<Text variant='secondary'>PNG - 6.1MB</Text>} visual={<Icon name='document-doc'/>}/>
          <Select label='Select a service case' style={{ width: '15rem' }}>
            <Option value=''>Select…</Option>
            <Option value='Make payment' selected>
              Make payment
            </Option>
            <Option value='Facilities'>Facilities</Option>
          </Select>
        </Flex>
      </Modal>);
    };
    const onAssociateWithCase = () => {
        create(MyModal);
    };
    const actions = [
        {
            text: 'Associate with case',
            id: 'Associate with case',
            onClick: () => {
                action('Associate with case');
                onAssociateWithCase();
            }
        },
        {
            text: 'Download',
            id: 'Download',
            onClick: () => {
                action('Download');
            }
        }
    ];
    const mockChatMessages = useMemo(() => {
        return [
            ...mockChatMessagesJson.map(message => {
                const { messagePrivacy, ...restMessageData } = message;
                if (messagePrivacy) {
                    restMessageData.messageHeader = {
                        content: <span>{messagePrivacy}</span>,
                        meta: <Link href='/'>I-12345</Link>
                    };
                }
                if (restMessageData.attachments) {
                    restMessageData.attachments = restMessageData.attachments.map((item) => {
                        return {
                            ...item,
                            actions
                        };
                    });
                }
                return restMessageData;
            })
        ];
    }, []);
    const conversationRef = useRef(null);
    const timers = useRef([]);
    useEffect(() => {
        return () => {
            timers.current.forEach(clearTimeout);
        };
    }, []);
    const [open, setOpen] = useState(false);
    const [lightBoxItems, setLightBoxItems] = useState(mockData.slice(0, 4));
    const [lightBoxMessageItems, setLightBoxMessageItems] = useState([]);
    const [composerAttachment, setComposerAttachment] = useState([]);
    const messageLightBoxOpen = useRef(false);
    const [unreadMessageCount, setUnreadMessageCount] = useState(0);
    const [chatMessages, setChatMessages] = useState(LiveChatConversation.map(message => {
        if (message.type === 'message' && message.attachments) {
            message.attachments = message.attachments.map((item) => {
                return {
                    ...item,
                    actions
                };
            });
        }
        return message;
    }));
    const [contextItems, setContextItems] = useState([]);
    const [contextLoading, setContextLoading] = useState(false);
    const [suggestedRepliesCollapsed, setSuggestedRepliesCollapsed] = useState(false);
    const [disableSuggestReply, setDisableSuggestReply] = useState(false);
    const onDeleteAttachment = useCallback((id) => {
        setComposerAttachment(prevAttachments => prevAttachments.filter(item => item.id !== id));
        setLightBoxItems(prevItem => prevItem.filter(item => item.id !== id));
    }, [setComposerAttachment]);
    useEffect(() => {
        return setComposerAttachment(mockData.slice(0, 4).map(item => {
            return {
                id: item.id,
                name: item.name,
                format: item.format,
                onDelete: onDeleteAttachment,
                onPreview: () => {
                    setOpen(true);
                }
            };
        }));
    }, []);
    const prevState = usePrevious(chatMessages);
    useEffect(() => {
        if (chatMessages &&
            prevState &&
            chatMessages.filter(({ senderType }) => senderType === 'customer').length >
                prevState.filter(({ senderType }) => senderType === 'customer').length)
            setDisableSuggestReply(false);
    }, [chatMessages]);
    useEffect(() => {
        setDisableSuggestReply(false);
    }, [args.genAIErrorState]);
    const appendMessage = (message) => {
        const incrementUnreadMessageCount = conversationRef.current?.isScrolledToLatest();
        setChatMessages(prevChatMessages => {
            const newMockMessage = {
                ...message,
                attachments: message.composerAttachment?.map((item) => {
                    return {
                        id: item.id,
                        name: item.name,
                        onPreview: () => {
                            messageLightBoxOpen.current = true;
                            setLightBoxMessageItems(message.composerAttachment?.map((item1) => {
                                const correspondingItem = mockData.find(item2 => item1.id.includes(item2.id));
                                return {
                                    ...correspondingItem,
                                    name: item1.name
                                };
                            }));
                            setOpen(true);
                        },
                        meta: `${getKindFromMimeType(getMimeTypeFromFile(item.format) ?? '').toUpperCase()} 0.5 MB`,
                        thumbnail: getKindFromMimeType(getMimeTypeFromFile(item.format) ?? '') === 'image'
                            ? 'https://images.unsplash.com/photo-1497752531616-c3afd9760a11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2100&q=80'
                            : undefined,
                        actions: [
                            {
                                id: 'item-1',
                                text: 'Associate with case'
                            },
                            {
                                id: 'item-2',
                                text: 'Download'
                            }
                        ]
                    };
                })
            };
            newMockMessage.id = `m-${message.id ? message.id : prevChatMessages.length}`;
            if (!incrementUnreadMessageCount &&
                prevChatMessages.filter(({ id }) => id === NewMessageSeparatorId).length === 0) {
                return [
                    ...prevChatMessages,
                    {
                        id: NewMessageSeparatorId,
                        type: 'system',
                        message: 'New messages',
                        variant: 'primary'
                    },
                    newMockMessage
                ];
            }
            return [...prevChatMessages, newMockMessage];
        });
        if (!incrementUnreadMessageCount) {
            setUnreadMessageCount(prevCount => prevCount + 1);
        }
        setComposerAttachment([]);
        setLightBoxItems([]);
    };
    useEffect(() => {
        if (args.simulateConversation) {
            const timeOutId = setTimeout(() => {
                if (mockChatMessages.length) {
                    appendMessage(mockChatMessages.shift());
                }
            }, 1500);
            return () => {
                clearTimeout(timeOutId);
            };
        }
    }, [chatMessages, args.simulateConversation]);
    const chatBanner = {
        messages: ['This is a public interaction and any responses will be public and visible'],
        variant: 'warning'
    };
    const bodyProps = {
        unreadMessageCount,
        handle: conversationRef,
        transcripts: [
            { id: createUID(), messages: BotConversation },
            { id: createUID(), messages: ClaimsAgentConversation }
        ],
        liveChat: !args.simulateConversation && args.typingIndicator
            ? [
                ...chatMessages,
                {
                    id: 'typingMessage',
                    type: 'typing',
                    avatarInfo: {
                        name: 'Ginger Ventura'
                    },
                    message: args.message,
                    senderId: 'gingerVentura',
                    senderType: 'customer'
                }
            ]
            : chatMessages,
        onScrollToButtonClick: () => {
            const timeOutId = window.setTimeout(() => {
                setChatMessages(prevChatMessages => prevChatMessages.filter(({ id }) => id !== NewMessageSeparatorId));
                timers.current = timers.current.filter(id => id !== timeOutId);
            }, 5000);
            timers.current.push(timeOutId);
            setUnreadMessageCount(0);
        },
        loadMore: action('Load more'),
        offset: 5,
        loading: args.loading,
        renderMarkdownContent: args.renderMarkdownContent
    };
    const chatComposerImperativeHandleRef = useRef(null);
    const [mountPopover, setMountPopover] = useState(false);
    const specialKeysConfig = {
        keys: ['//'],
        onSpecialKey: (e, key) => {
            action(`Event is  ${e}`)();
            action(`Typed special key is ${key}`)();
            if (chatComposerImperativeHandleRef.current) {
                setMountPopover(!mountPopover);
            }
        }
    };
    const insertPhrasesMessage = (message) => {
        if (chatComposerImperativeHandleRef.current) {
            chatComposerImperativeHandleRef.current.appendToMessage(message, 'specialKey');
            setMountPopover(false);
        }
    };
    useOuterEvent('mousedown', [chatComposerImperativeHandleRef?.current?.chatComposerRef?.current], () => {
        setMountPopover(false);
    });
    const [search, setSearch] = useState('');
    const [isOpen, setIsOpen] = useState(false);
    const searchEleRef = useRef(null);
    const [announcement, setAnnouncement] = useState('');
    const searchRegex = useMemo(() => {
        const escapedSearch = search.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
        return new RegExp(escapedSearch);
    }, [search]);
    const itemsToRender = useMemo(() => {
        return menuHelpers.mapTree(search
            ? menuHelpers.flatten(phrasesDisplayNames).filter(({ primary }) => {
                return searchRegex.test(primary);
            })
            : phrasesDisplayNames, item => {
            return {
                ...item
            };
        });
    }, [search, phrasesDisplayNames, searchRegex]);
    useEffect(() => {
        if (isOpen) {
            searchEleRef?.current?.focus();
        }
    }, [isOpen, searchEleRef.current]);
    const menuID = createUID();
    const menuListID = `${menuID}--list`;
    const [buttonEl, setButtonEl] = useElement(null);
    const [popoverEl, setPopoverEl] = useElement(null);
    const [currentReply, setCurrentReply] = useState(suggestedReplies?.[0]?.id || '');
    const [replies, setReplies] = useState(suggestedReplies);
    const [bargeIn, setBargeIn] = useState(true);
    useOuterEvent('mousedown', [popoverEl, buttonEl], () => {
        setIsOpen(false);
        setSearch('');
    });
    useEscape(() => {
        setIsOpen(false);
    });
    useEffect(() => {
        setBargeIn(args.enableJoinConversationButton ?? false);
    }, [args.enableJoinConversationButton]);
    const composerChildren = (<>
      <Button ref={setButtonEl} onClick={() => setIsOpen(cur => !cur)} variant='secondary' disabled={args.disableChat}>
        <Flex container={{ alignItems: 'center', gap: 1 }}>
          <Text>Phrases</Text>
          <Icon name='arrow-micro-down'/>
        </Flex>
      </Button>

      <Popover show={isOpen} ref={setPopoverEl} target={buttonEl}>
        <Menu id={menuID} listId={menuListID} mode='action' variant='flyout' items={itemsToRender} role='listbox' onItemClick={id => {
            insertPhrasesMessage(phrasesMessages.filter(message => message.id === id)[0].message);
            setAnnouncement('Phrase inserted');
            setIsOpen(false);
            setSearch('');
        }} accent={search ? searchRegex : undefined} focusControlEl={searchEleRef.current || undefined} footer={<SearchInput ref={searchEleRef} onSearchChange={setSearch} value={search} role='searchbox' searchInputAriaLabel='Start typing to search.'/>}/>
      </Popover>
    </>);
    const composerProps = {
        ref: chatComposerImperativeHandleRef,
        maxAttachments: args.maxAttachments,
        attachments: args.showAttachments ? composerAttachment : [],
        specialKeysConfig,
        showEmoji: true,
        disabled: args.disableChat,
        disableSuggestReply: args.enableJoinConversationButton || disableSuggestReply,
        onAddAttachment: () => {
            setComposerAttachment([
                ...composerAttachment,
                {
                    id: `doc ${composerAttachment.length}`,
                    name: `${composerAttachment.length} statement.docx`,
                    format: 'docx',
                    onDelete: onDeleteAttachment,
                    onPreview: () => {
                        setOpen(true);
                    }
                }
            ]);
            setLightBoxItems([
                ...lightBoxItems,
                {
                    id: `doc ${composerAttachment.length}`,
                    name: `${composerAttachment.length} statement.docx`,
                    format: 'docx',
                    description: 'Descriptive text about Pega document',
                    src: null
                }
            ]);
        },
        maxLength: args.maxLength,
        placeholder: args.placeholder,
        defaultMessage: args.defaultMessage,
        onSend: (message) => {
            action(`onAppendMessage: ${message}`)();
            appendMessage({
                senderType: 'agent',
                direction: 'out',
                avatarInfo: {
                    name: 'Edward Green'
                },
                type: 'message',
                message,
                composerAttachment,
                timeStamp: '2:08'
            });
        },
        onSuggestReplyClick: () => {
            const newReplyId = 'genAI';
            setDisableSuggestReply(true);
            setSuggestedRepliesCollapsed(false);
            setCurrentReply(newReplyId);
            setReplies(prev => {
                return [
                    {
                        id: newReplyId,
                        loading: true,
                        type: 'genAIReply'
                    },
                    ...prev.filter(reply => reply.type !== 'genAIReply')
                ];
            });
            setTimeout(() => {
                if (args.genAIErrorState === 'No suggestions') {
                    setReplies(prev => {
                        return [
                            {
                                id: newReplyId,
                                message: 'No suggestions',
                                errorType: 'noSuggestions',
                                type: 'genAIReply'
                            },
                            ...prev.filter(reply => reply.type !== 'genAIReply')
                        ];
                    });
                }
                else if (args.genAIErrorState === 'Error') {
                    setReplies(prev => {
                        return [
                            {
                                id: newReplyId,
                                message: 'Failed to retrieve the data',
                                errorType: 'error',
                                type: 'genAIReply'
                            },
                            ...prev.filter(reply => reply.type !== 'genAIReply')
                        ];
                    });
                    setDisableSuggestReply(false);
                }
                else {
                    setReplies(prev => {
                        return [
                            {
                                id: newReplyId,
                                message: 'Happy to help. Is there anything else I can help with?',
                                confidence: 75,
                                type: 'genAIReply'
                            },
                            ...prev.filter(reply => reply.type !== 'genAIReply')
                        ];
                    });
                }
            }, 1000);
        },
        children: composerChildren,
        joinConversation: bargeIn
            ? {
                onClick: () => {
                    setBargeIn(false);
                },
                disabled: false
            }
            : undefined
    };
    const suggestedReplyPickerProps = {
        replies,
        onSelect: (suggestedReply) => {
            if (!isReplyErrorState(suggestedReply) && !isReplyLoadingState(suggestedReply))
                chatComposerImperativeHandleRef.current?.appendToMessage(suggestedReply.message, 'cursor');
        },
        collapsed: suggestedRepliesCollapsed,
        onExpandCollapse: () => {
            setSuggestedRepliesCollapsed(prev => !prev);
        },
        showNotification: true,
        currentReplyId: currentReply,
        onReplyChange: id => {
            setCurrentReply(id);
        },
        onSend: (message) => {
            action(`onAppendMessage: ${message}`)();
            appendMessage({
                senderType: 'agent',
                direction: 'out',
                avatarInfo: {
                    name: 'Edward Green'
                },
                type: 'message',
                message,
                timeStamp: '2:08'
            });
        }
    };
    return (<Flex container={{
            justify: 'center'
        }} style={{
            height: args.chatHeight || 'calc(100vh)',
            width: args.chatWidth || '30rem',
            margin: 'auto'
        }}>
      <VisuallyHiddenText aria-live='assertive'>{announcement}</VisuallyHiddenText>
      <Chat header={{
            title: Channels.options[args.selectedChannel || 'LiveChat'].title,
            icon: Channels.options[args.selectedChannel || 'LiveChat'].icon,
            customer: 'Ginger Ventura',
            authenticated: true,
            sentiment: { variant: 'positive' },
            context: {
                items: contextItems,
                onClick: () => {
                    setContextLoading(true);
                    setTimeout(() => {
                        setContextItems(contextItemsMock);
                        setContextLoading(false);
                    }, 1000);
                },
                loading: contextLoading
            },
            actions: [
                { id: 'action-1', primary: 'Transfer' },
                { id: 'action-2', primary: 'End chat' }
            ]
        }} banner={args.showChatBanner ? chatBanner : undefined} body={bodyProps} suggestedReplyPicker={args.enableJoinConversationButton ? undefined : suggestedReplyPickerProps} composer={composerProps}/>
      {open && (<Lightbox items={messageLightBoxOpen.current ? lightBoxMessageItems : lightBoxItems} cycle onAfterClose={() => {
                setOpen(false);
                messageLightBoxOpen.current = false;
            }} onItemDownload={() => { }}/>)}
    </Flex>);
};
StandardChat.args = {
    maxAttachments: 2,
    selectedChannel: 'LiveChat',
    showChatBanner: true,
    disableChat: false,
    simulateConversation: false,
    typingIndicator: false,
    message: '',
    placeholder: 'Enter message',
    defaultMessage: 'Greetings! Hope you are having a great time, Please reach out to us for any help, Thanks!',
    maxLength: 280,
    loading: false,
    showAttachments: true,
    genAIErrorState: 'No error',
    enableJoinConversationButton: true,
    renderMarkdownContent: false
};
StandardChat.argTypes = {
    maxAttachments: { control: { type: 'number' } },
    showAttachments: { control: { type: 'boolean' } },
    selectedChannel: { options: ['LiveChat', 'Twitter', 'Facebook'], control: { type: 'select' } },
    showChatBanner: { control: { type: 'boolean' } },
    disableChat: { control: { type: 'boolean' } },
    simulateConversation: { control: { type: 'boolean' } },
    typingIndicator: { control: { type: 'boolean' } },
    message: { control: { type: 'text' } },
    placeholder: { control: { type: 'text' } },
    defaultMessage: { control: { type: 'text' } },
    maxLength: { control: { type: 'number' } },
    loading: { control: { type: 'boolean' } },
    genAIErrorState: {
        options: ['No error', 'No suggestions', 'Error'],
        control: { type: 'select' }
    },
    enableJoinConversationButton: { control: { type: 'boolean' } },
    renderMarkdownContent: { control: { type: 'boolean' } }
};
StandardChat.parameters = {
    layout: 'fullscreen'
};
//# sourceMappingURL=Chat.stories.jsx.map