import { useEffect, useMemo, useState } from 'react';
import { action } from '@storybook/addon-actions';
import { GenAICoach, GenAIMessage, isCoachMessage, isUserMessage } from '@pega/cosmos-react-work';
import { createUID } from '@pega/cosmos-react-core';
import { coachOptionsMock, genAICoachMessageMockData, initialSuggestedMessagesMockData, StyledContainer, suggestionsMock, conversationHistorySummaryData, StyledCoachList, attachmentsMock } from './GenAICoach.mocks';
export default {
    title: 'Work/GenAICoach',
    component: GenAICoach
};
export const GenAICoachDemo = (args) => {
    const [loading, setLoading] = useState(false);
    const [messages, setMessages] = useState([]);
    const [initialSuggestedMessages, setInitialSuggestedMessages] = useState([]);
    const [showHistory, setShowHistory] = useState(false);
    const [progressiveLoading, setProgressiveLoading] = useState(false);
    const [selectedItemInHistory, setSelectedItemInHistory] = useState(conversationHistorySummaryData[0].conversations[1].id);
    const [historyViewData, setHistoryViewData] = useState(conversationHistorySummaryData);
    const [inFullPage, setInFullPage] = useState(false);
    const [attachments, setAttachments] = useState([]);
    const [attachmentsForPreview, setAttachmentsForPreview] = useState([]);
    const [openPreview, setOpenPreview] = useState(false);
    const sendMessage = (userMessage) => {
        setHistoryViewData(prev => {
            let movedItem;
            prev.forEach((section, index) => {
                const chatThreadIndex = section.conversations.findIndex(item => item.id === selectedItemInHistory);
                if (chatThreadIndex !== -1) {
                    movedItem = section.conversations.splice(chatThreadIndex, 1)[0];
                    if (section.conversations.length === 0) {
                        prev.splice(index, 1);
                    }
                }
            });
            if (movedItem)
                prev[0].conversations = [movedItem, ...prev[0].conversations];
            return prev;
        });
        action(`Message from composer: ${Boolean(userMessage?.fromComposer)}`);
        setMessages((prevMessages) => {
            const files = [];
            userMessage?.attachmentIds?.forEach(id => {
                const attachment = attachments.find(item => item.id === id);
                if (attachment) {
                    files.push({
                        id,
                        onPreview: attachment.onPreview,
                        displayText: attachment.name,
                        value: attachment.name
                    });
                }
            });
            return [
                ...prevMessages,
                {
                    ...userMessage,
                    attachments: files,
                    from: 'user'
                }
            ];
        });
        if (userMessage?.attachmentIds?.length) {
            setAttachments([]);
        }
    };
    const handleFeedback = (messageId, feedback) => {
        if (feedback)
            action('Submit')(`${messageId}:${feedback}`);
        else
            action('Cancel')(`${messageId}`);
    };
    const initialize = () => {
        setLoading(true);
        setTimeout(() => {
            setInitialSuggestedMessages(initialSuggestedMessagesMockData);
            setMessages([]);
            setLoading(false);
        }, 1000);
        setShowHistory(false);
    };
    useEffect(() => {
        initialize();
    }, []);
    useEffect(() => {
        if (messages.length > 0 && isUserMessage(messages[messages.length - 1])) {
            setTimeout(() => {
                setMessages([
                    ...messages,
                    { loading: true, from: 'coach', coachName: 'Pega Gen AI™ coach', id: '1234' }
                ]);
            }, 1000);
            setTimeout(() => {
                const random = Math.floor(Math.random() * 2);
                setMessages([...messages, { ...genAICoachMessageMockData[random], id: createUID() }]);
            }, 2000);
        }
    }, [messages.length]);
    const handleReaction = (id, updatedReaction) => {
        setMessages(prevMessages => prevMessages.map(message => message.id === id
            ? {
                ...message,
                feedback: {
                    reaction: updatedReaction,
                    onReaction: (messageId, newReaction) => handleReaction(messageId, newReaction),
                    onFeedbackComplete: handleFeedback
                }
            }
            : message));
    };
    const messagesProp = useMemo(() => {
        if (args.showMessageLoading)
            return [
                ...messages,
                {
                    id: '1',
                    from: 'coach',
                    coachName: 'Pega GenAI™ Coach',
                    loading: true
                }
            ];
        if (args.showErrorInMessage)
            return [
                ...messages,
                {
                    id: '2',
                    from: 'coach',
                    coachName: 'Pega GenAI™ Coach',
                    error: 'Error retrieving response'
                }
            ];
        return messages.map(item => {
            if (isCoachMessage(item))
                return {
                    ...item,
                    feedback: {
                        onReaction: handleReaction,
                        reaction: item.feedback?.reaction,
                        onFeedbackComplete: handleFeedback
                    }
                };
            return item;
        });
    }, [args.showErrorInMessage, args.showMessageLoading, messages]);
    const onAddAttachment = (files) => {
        setAttachments(files.map(file => {
            const id = createUID();
            return {
                id,
                name: file.name,
                format: file.name.split('.').pop(),
                onDelete: () => {
                    setAttachments(prev => prev.filter(item => item.id !== id));
                },
                onCancel: () => {
                    setAttachments(prev => prev.filter(item => item.id !== id));
                },
                onPreview: () => {
                    setAttachmentsForPreview(files.map(fileForPreview => {
                        return {
                            id: createUID(),
                            name: fileForPreview.name,
                            description: 'Descriptive text about File 1',
                            format: fileForPreview.name.split('.').pop(),
                            src: URL.createObjectURL(fileForPreview)
                        };
                    }));
                    setOpenPreview(true);
                },
                file
            };
        }));
    };
    return (<StyledContainer fullPageView={args.showFullPageViewWithHistory}>
      <GenAICoach loading={loading} coachOptions={coachOptionsMock} onCoachChange={initialize} messages={messagesProp} initialSuggestedMessages={initialSuggestedMessages} onSend={sendMessage} suggestions={suggestionsMock} variant={{ placement: 'fullpage' }} error={args.showError ? 'Error retreving data' : undefined} guidedMode={args.guidedMode} onLayoutChange={(inFullPageArg) => {
            setInFullPage(inFullPageArg);
        }} onAddAttachment={onAddAttachment} attachments={attachments} attachmentsError={args.attachmentsError} lightboxPreviewProps={openPreview
            ? {
                items: attachmentsForPreview,
                cycle: true,
                onAfterClose: () => {
                    setOpenPreview(false);
                },
                onItemDownload: () => { }
            }
            : undefined} actions={args.showActions
            ? {
                items: [
                    {
                        id: '1',
                        text: 'New chat',
                        onClick: () => {
                            initialize();
                        }
                    },
                    {
                        id: '2',
                        text: 'History',
                        onClick: () => {
                            setShowHistory(true);
                        }
                    }
                ]
            }
            : undefined} conversationHistory={showHistory
            ? {
                data: args.showLoadingInHistory || args.showEmptyStateInHistory ? [] : historyViewData,
                onDismiss: () => {
                    setShowHistory(false);
                },
                loading: args.showLoadingInHistory ? true : progressiveLoading,
                loadMore: () => {
                    setProgressiveLoading(true);
                    setTimeout(() => {
                        setProgressiveLoading(false);
                    }, 2000);
                },
                error: args.showErrorStateInHistory,
                onItemClick: conversationId => {
                    setSelectedItemInHistory(conversationId);
                    if (!inFullPage)
                        setShowHistory(false);
                    setMessages(genAICoachMessageMockData);
                },
                selectedItemId: selectedItemInHistory
            }
            : undefined}/>
    </StyledContainer>);
};
GenAICoachDemo.args = {
    showMessageLoading: false,
    showErrorInMessage: false,
    showError: false,
    guidedMode: false,
    showActions: false,
    showLoadingInHistory: false,
    showErrorStateInHistory: '',
    showEmptyStateInHistory: false,
    showFullPageViewWithHistory: false,
    attachmentsError: ''
};
GenAICoachDemo.argTypes = {
    showMessageLoading: { control: { type: 'boolean' } },
    showErrorInMessage: { control: { type: 'boolean' } },
    showError: { control: { type: 'boolean' } },
    guidedMode: { control: { type: 'boolean' } },
    showActions: { control: { type: 'boolean' } },
    showLoadingInHistory: { control: { type: 'boolean' } },
    showErrorStateInHistory: { control: { type: 'text' } },
    showEmptyStateInHistory: { control: { type: 'boolean' } },
    showFullPageViewWithHistory: { control: { type: 'boolean' } },
    attachmentsError: { control: { type: 'text' } }
};
export const GenAICoachMessageDemo = (args) => {
    const [message, setMessage] = useState();
    useEffect(() => {
        const handleFeedback = (messageId, feedback) => {
            if (feedback)
                action('Submit')(`${messageId}:${feedback}`);
            else
                action('Cancel')(`${messageId}`);
        };
        let updatedMessage = genAICoachMessageMockData.find(v => v.from === args.from);
        if (updatedMessage?.from === 'user' && args.showAttachments) {
            updatedMessage = {
                ...updatedMessage,
                attachments: attachmentsMock
            };
        }
        if (updatedMessage?.from === 'coach') {
            const handleReaction = (id, updatedReaction) => {
                setMessage(prevMessage => {
                    return {
                        ...prevMessage,
                        feedback: {
                            reaction: updatedReaction,
                            onReaction: handleReaction,
                            onFeedbackComplete: args.onFeedbackComplete ? args.onFeedbackComplete : handleFeedback
                        }
                    };
                });
            };
            if (args.showMessageLoading)
                updatedMessage = {
                    from: 'coach',
                    id: createUID(),
                    coachName: updatedMessage.coachName,
                    loading: true
                };
            else if (args.showErrorInMessage) {
                updatedMessage = {
                    from: 'coach',
                    id: createUID(),
                    coachName: updatedMessage.coachName,
                    error: 'Error retreiving response'
                };
            }
            else if (!args.showSuggestions) {
                updatedMessage = {
                    ...updatedMessage,
                    suggestions: undefined
                };
            }
            if (args.showFeedback)
                updatedMessage = {
                    ...updatedMessage,
                    feedback: {
                        onReaction: handleReaction,
                        reaction: updatedMessage.feedback?.reaction,
                        onFeedbackComplete: args.onFeedbackComplete ? args.onFeedbackComplete : handleFeedback
                    }
                };
            if (args.onSend) {
                updatedMessage = { ...updatedMessage, onSend: args.onSend };
            }
        }
        setMessage(updatedMessage);
    }, [
        args.from,
        args.showErrorInMessage,
        args.showFeedback,
        args.showMessageLoading,
        args.showSuggestions,
        args.showAttachments
    ]);
    return <StyledCoachList>{message && <GenAIMessage {...message}/>}</StyledCoachList>;
};
GenAICoachMessageDemo.args = {
    from: 'coach',
    showMessageLoading: false,
    showErrorInMessage: false,
    showSuggestions: false,
    showFeedback: false,
    showAttachments: false
};
GenAICoachMessageDemo.argTypes = {
    from: { options: ['coach', 'user'], control: { type: 'select' } },
    showMessageLoading: { control: { type: 'boolean' } },
    showErrorInMessage: { control: { type: 'boolean' } },
    showSuggestions: { control: { type: 'boolean' } },
    showFeedback: { control: { type: 'boolean' } },
    showAttachments: { control: { type: 'boolean' } }
};
//# sourceMappingURL=GenAICoach.stories.jsx.map