import React from "react";
import { CometChatTheme, CometChatUIEventHandler, CometChatUIEvents, DataSourceDecorator, MessageEvents, localize } from "../../shared";
import { CometChat } from "@cometchat/chat-sdk-react-native";
import { State } from "../utils";
import { MessageStatusConstants, ReceiverTypeConstants, ViewAlignment } from "../../shared/constants/UIKitConstants";
import { TouchableOpacity, View, Text, ScrollView, Keyboard } from "react-native";
import CometChatAICard from "../../shared/views/CometChatAICard/CometChatAICard";
import { getCardViewStyle, getRepliesStyle, getRepliesWrapperStyle } from "../style";
export class AISmartRepliesExtensionDecorator extends DataSourceDecorator {
    configuration;
    user;
    group;
    theme = new CometChatTheme({});
    isPannelVisible = false;
    repliesView;
    loadingStateText = localize("GENERATING_REPLIES");
    errorStateText = localize("SOMETHING_WRONG");
    emptyStateText = localize("NO_MESSAGES_FOUND");
    cardViewStyle = {};
    keyboardDidShowListener;
    keyboardDidHideListener;
    loggedInUser;
    LISTENER_ID = "aismartlistener__listener";
    constructor(dataSource, configuration) {
        super(dataSource);
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.hideOnKeyboardShow);
        // this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.showOnKeyboardShow);
        this.configuration = configuration;
        this.cardViewStyle = getCardViewStyle(this.theme, this.configuration?.smartRepliesStyle);
        setTimeout(() => {
            this.addMessageListener();
        }, 1000);
    }
    getId() {
        return "aismartreply";
    }
    getAIOptions(user, group, theme, id, AIOptionsStyle) {
        this.user = user;
        this.group = group;
        if (!id?.parentMessageId) {
            const messageComposerActions = super.getAIOptions(user, group, theme, id, AIOptionsStyle);
            let newAction = {
                title: localize("SUGGEST_A_REPLY"),
                onPress: () => {
                    this.onButtonClick();
                },
                id: "smart-replies",
                iconURL: '',
                iconTint: '',
                titleColor: this.configuration?.smartRepliesStyle?.buttonTextColor || AIOptionsStyle.listItemTitleColor,
                titleFont: this.configuration?.smartRepliesStyle?.buttonTextFont || AIOptionsStyle.listItemTitleFont,
                background: this.configuration?.smartRepliesStyle?.backgroundColor || AIOptionsStyle.listItemBackground,
                cornerRadius: this.configuration?.smartRepliesStyle?.buttonBorderRadius || AIOptionsStyle.listItemBorderRadius,
            };
            messageComposerActions.push(newAction);
            return messageComposerActions;
        }
        else {
            return super.getAIOptions(user, group, theme, id, AIOptionsStyle);
        }
    }
    getLoadingView() {
        let LoadingView = this.configuration?.LoadingStateView;
        return (<CometChatAICard state={State.loading} style={this.configuration?.smartRepliesStyle} loadingIconURL={this.configuration?.loadingIconURL} loadingStateText={this.loadingStateText}>
        {LoadingView ? <LoadingView /> : null}
      </CometChatAICard>);
    }
    getEmptyView() {
        let EmptyView = this.configuration?.EmptyStateView;
        return (<CometChatAICard state={State.empty} style={this.configuration?.smartRepliesStyle} emptyIconURL={this.configuration?.emptyIconURL} emptyStateText={this.emptyStateText}>
        {EmptyView ? <EmptyView /> : null}
      </CometChatAICard>);
    }
    getErrorView(error) {
        return (<CometChatAICard state={State.error} style={this.configuration?.smartRepliesStyle} errorIconURL={this.configuration?.errorIconURL} errorStateText={this.errorStateText}>
        {this.configuration?.ErrorStateView ? this.configuration?.ErrorStateView(error) : null}
      </CometChatAICard>);
    }
    editReply(reply) {
        CometChatUIEventHandler.emitUIEvent(CometChatUIEvents.hidePanel, {
            alignment: ViewAlignment.composerBottom,
            child: () => (null),
        });
        this.isPannelVisible = false;
        CometChatUIEventHandler.emitUIEvent(CometChatUIEvents.ccComposeMessage, { text: reply });
        this.keyboardDidShowListener?.remove();
        this.keyboardDidHideListener?.remove();
    }
    hideOnKeyboardShow = () => {
        if (this.isPannelVisible) {
            CometChatUIEventHandler.emitUIEvent(CometChatUIEvents.hidePanel, {
                alignment: ViewAlignment.composerBottom,
                child: () => (null),
            });
        }
    };
    showOnKeyboardShow = () => {
        if (this.isPannelVisible) {
            CometChatUIEventHandler.emitUIEvent(CometChatUIEvents.hidePanel, {
                alignment: ViewAlignment.composerBottom,
                child: () => this.repliesView,
            });
        }
    };
    getSmartReplies() {
        return new Promise((resolve, reject) => {
            let receiverId = this.user ? this.user?.getUid() : this.group?.getGuid();
            let receiverType = this.user ? ReceiverTypeConstants.user : ReceiverTypeConstants.group;
            if (this.configuration?.customView) {
                CometChat.getSmartReplies(receiverId, receiverType).then((response) => {
                    this.configuration.customView(response).then((res) => {
                        return resolve((<View>{res}</View>));
                    })
                        .catch((err) => {
                        return reject(err);
                    });
                })
                    .catch((err) => {
                    return reject(err);
                });
            }
            else {
                CometChat.getSmartReplies(receiverId, receiverType).then((response) => {
                    let view = [];
                    Object.keys(response).forEach((reply) => {
                        if (response[reply] && response[reply] != "") {
                            view.push((<TouchableOpacity style={getRepliesWrapperStyle(this.theme, this.configuration?.smartRepliesStyle, this.configuration?.listItemStyle)} key={response[reply]} // Make sure to set a unique key for each item
                             onPress={() => this.editReply(response[reply])}>
                  <Text style={getRepliesStyle(this.theme, this.configuration?.smartRepliesStyle, this.configuration?.listItemStyle)}>{response[reply]}</Text>
                </TouchableOpacity>));
                        }
                    });
                    return resolve((<View>{view}</View>));
                })
                    .catch((err) => {
                    return reject(err);
                });
            }
        });
    }
    onButtonClick = () => {
        this.showDefaultPanel(State.loading);
        this.getSmartReplies().then((replies) => {
            if (!replies || (replies?.length && replies.length <= 0)) {
                this.showDefaultPanel(State.empty);
            }
            else {
                this.repliesView = (<View style={{ width: this.cardViewStyle?.width || "100%", height: this.cardViewStyle?.height || 200, backgroundColor: this.cardViewStyle?.backgroundColor, borderRadius: this.cardViewStyle?.borderRadius, ...this.cardViewStyle?.border, marginTop: 8 }}>
          <ScrollView style={{ height: "100%", width: "100%" }}>
            {replies}
          </ScrollView>


        </View>);
                CometChatUIEventHandler.emitUIEvent(CometChatUIEvents.showPanel, {
                    alignment: ViewAlignment.composerBottom,
                    child: () => this.repliesView,
                });
            }
            this.isPannelVisible = true;
        })
            .catch((err) => {
            this.showDefaultPanel(State.error, err);
        });
    };
    showDefaultPanel(state = State.loading, error) {
        CometChatUIEventHandler.emitUIEvent(CometChatUIEvents.showPanel, {
            alignment: ViewAlignment.composerBottom,
            child: () => (<View style={{
                    width: this.cardViewStyle?.width || "100%", height: this.cardViewStyle?.height || 160,
                    backgroundColor: this.cardViewStyle?.backgroundColor, borderRadius: this.cardViewStyle?.borderRadius,
                    ...this.cardViewStyle?.border,
                    justifyContent: "center", alignItems: "center"
                }}>
          {state == State.loading ? this.getLoadingView() : (state == State.empty ? this.getEmptyView() : this.getErrorView(error))}
        </View>)
        });
        this.isPannelVisible = true;
    }
    closePanel = () => {
        CometChatUIEventHandler.emitUIEvent(CometChatUIEvents.hidePanel, {
            alignment: ViewAlignment.composerBottom,
            child: () => (null),
        });
    };
    closeIfMessageReceived(message) {
        if (message?.getReceiverId() === this.loggedInUser?.getUid()) {
            this.closePanel();
        }
    }
    addMessageListener() {
        CometChat.getLoggedinUser().then((user) => {
            if (user) {
                this.loggedInUser = user;
            }
        });
        CometChatUIEventHandler.addMessageListener(this.LISTENER_ID, {
            onTextMessageReceived: (message) => {
                this.closeIfMessageReceived(message);
            },
            onCustomMessageReceived: (message) => {
                this.closeIfMessageReceived(message);
            },
            onMediaMessageReceived: (message) => {
                this.closeIfMessageReceived(message);
            },
            onFormMessageReceived: (formMessage) => {
                this.closeIfMessageReceived(formMessage);
            },
            onCardMessageReceived: (cardMessage) => {
                this.closeIfMessageReceived(cardMessage);
            },
            onSchedulerMessageReceived: (schedulerMessage) => {
                this.closeIfMessageReceived(schedulerMessage);
            },
            onCustomInteractiveMessageReceived: (customInteractiveMessage) => {
                this.closeIfMessageReceived(customInteractiveMessage);
            }
        });
        CometChatUIEventHandler.addMessageListener(MessageEvents.ccActiveChatChanged + "_AISmartReplies", {
            ccActiveChatChanged: (data) => {
                // console.log("_________ACTIVE CHAT CHANGED IN AI CONVERSATION SUMMARY")
                // this.currentMessage = data.message!;
                // this.user = data.user!;
                // this.group = data.group!;
                // this.unreadMessageCount = data.unreadMessageCount ?? 0;
                // if (this.unreadMessageCount >= (this.configuration?.unreadMessageThreshold ?? 30)) {
                //   this.loadConversationSummary();
                // }
            },
            ccMessageSent: ({ message, status }) => {
                if (status == MessageStatusConstants.success && message?.sender?.uid == this.loggedInUser?.uid) {
                    this.closePanel();
                }
            }
        });
    }
}
//# sourceMappingURL=AISmartRepliesDecorator.js.map