import { Fragment, Host, h } from "@stencil/core";
import { chatsStore, configStore, deviceModeStore, profilePanelStore, selectedChatStore, userStore } from "../../store/store";
import { ZIconButton } from "../internal-component/z-icon-button";
import { syncMessage, syncTags, updateChat, updateUser } from "../../api";
import { persistUser } from "../../utils/cache";
import { joinRoom, leaveRoom } from "../../utils/socket";
import { serviceReadMessage, serviceUnReadMessage } from "../../store/message";
import { getChatChannelPictureUrl, getChatName, getChatPicture } from "../../store/chat";
import { handleError } from "../../store/dialog";
import { ZToggle } from "../internal-component/z-toggle";
import { ZAvatarGroup } from "../internal-component/z-avatar-group";
import { useTranslation } from "../../utils/utils";
export class ChatHeader {
    disposeSelectedChatListener;
    disposeUserListener;
    isPinLoading = false;
    isSpamLoading = false;
    isReadLoading = false;
    isPin = false;
    isSpam = false;
    isUnRead = false;
    selectedValue = 'admin';
    async componentDidLoad() {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (selectedChat) {
            this.isPin = selectedChat.pin;
            this.isSpam = selectedChat.spam;
            const isRead = await serviceReadMessage(selectedChat.id);
            this.isUnRead = !isRead;
        }
    }
    async componentWillLoad() {
        this.disposeSelectedChatListener = selectedChatStore.onChange('selectedChat', async (newChat) => {
            if (!newChat) {
                this.isPin = false;
                this.isSpam = false;
                this.isUnRead = false;
                return;
            }
            this.isPin = newChat.pin;
            this.isSpam = newChat.spam;
            const isRead = await serviceReadMessage(newChat.id);
            this.isUnRead = !isRead;
        });
        //Watch user change
        this.disposeUserListener = userStore.onChange('user', async (newUser) => {
            if (!newUser) {
                this.selectedValue = 'admin';
                return;
            }
            this.selectedValue = newUser.context === 'contactadmin' ? 'admin' : 'bot';
        });
    }
    disconnectedCallback() {
        if (this.disposeSelectedChatListener)
            this.disposeSelectedChatListener();
        if (this.disposeUserListener)
            this.disposeUserListener();
    }
    handleBackToChatList = () => {
        const selectedChat = selectedChatStore.get('selectedChat');
        selectedChatStore.reset();
        profilePanelStore.reset();
        if (selectedChat && selectedChat.id) {
            leaveRoom(selectedChat.id);
        }
    };
    handleShowProfile = () => {
        if (deviceModeStore.get('mode') !== 'desktop') {
            profilePanelStore.set('isShowProfile', true);
        }
    };
    handleShowProfileTicket = () => {
        if (deviceModeStore.get('mode') !== 'desktop') {
            profilePanelStore.set('isShowProfile', true);
        }
        profilePanelStore.set('isSelectTab', 'ticket');
    };
    handleToggleReadMessageClick = async () => {
        try {
            this.isReadLoading = true;
            const selectedChat = selectedChatStore.get('selectedChat');
            const selectedChatId = selectedChat ? selectedChat.id : '';
            const isSuccess = this.isUnRead ? await serviceReadMessage(selectedChatId) : await serviceUnReadMessage(selectedChatId);
            if (isSuccess) {
                this.isUnRead = !this.isUnRead;
            }
        }
        catch (error) {
            handleError(error, 'Failed to toggle read message status');
        }
        finally {
            this.isReadLoading = false;
        }
    };
    handleSearchMessageClick = () => {
        selectedChatStore.set('isSearchMessage', true);
    };
    handleSyncChatMessage = async () => {
        try {
            selectedChatStore.set('isSyncingMessage', true);
            const selectedChat = selectedChatStore.get('selectedChat');
            const selectedChatId = selectedChat ? selectedChat.id : '';
            const response = await syncMessage({ sessionId: selectedChatId });
            selectedChatStore.set('syncMessageJobId', response.job_id);
            joinRoom(response.job_id, '/sync');
        }
        catch (error) {
            handleError(error, 'Failed to sync chat message');
        }
    };
    handleSyncTags = async () => {
        try {
            selectedChatStore.set('isSyncingTag', true);
            const selectedChat = selectedChatStore.get('selectedChat');
            const selectedChatId = selectedChat ? selectedChat.id : '';
            const response = await syncTags({ sessionId: selectedChatId });
            selectedChatStore.set('syncTagJobId', response.job_id);
            joinRoom(response.job_id, '/sync');
        }
        catch (error) {
            handleError(error, 'Failed to sync tags');
        }
    };
    handleTogglePinChatClick = async () => {
        try {
            this.isPinLoading = true;
            const _pin = !this.isPin;
            const selectedChat = selectedChatStore.get('selectedChat');
            const selectedChatId = selectedChat ? selectedChat.id : '';
            const { code } = await updateChat({
                sessionId: selectedChatId,
                pin: _pin,
            });
            if (code === 'chat-updated') {
                selectedChatStore.set('selectedChat', {
                    ...selectedChatStore.get('selectedChat'),
                    pin: _pin,
                });
                const pinChats = chatsStore
                    .get('chats')
                    .map(chat => {
                    if (chat.id === selectedChatId) {
                        return {
                            ...chat,
                            pin: _pin,
                        };
                    }
                    return chat;
                })
                    .sort((a, b) => {
                    if (a.pin !== b.pin) {
                        return a.pin ? -1 : 1;
                    }
                    const aTime = a.last_message_at ? new Date(a.last_message_at).getTime() : 0;
                    const bTime = b.last_message_at ? new Date(b.last_message_at).getTime() : 0;
                    return bTime - aTime;
                });
                chatsStore.set('chats', pinChats);
                this.isPin = _pin;
            }
        }
        catch (error) {
            handleError(error, 'Failed to pin chat');
        }
        finally {
            this.isPinLoading = false;
        }
    };
    handleToggleSpamChatClick = async () => {
        try {
            this.isSpamLoading = true;
            const _spam = !this.isSpam;
            const selectedChat = selectedChatStore.get('selectedChat');
            const selectedChatId = selectedChat ? selectedChat.id : '';
            const { code } = await updateChat({
                sessionId: selectedChatId,
                spam: _spam,
            });
            if (code === 'chat-updated') {
                //Requirement: No need to update chatStore waiting user refresh or click other chat
                const updateSelectedChat = {
                    ...selectedChatStore.get('selectedChat'),
                    spam: _spam,
                };
                selectedChatStore.set('selectedChat', updateSelectedChat);
                this.isSpam = _spam;
            }
        }
        catch (error) {
            handleError(error, 'Failed to toggle spam status');
        }
        finally {
            this.isSpamLoading = false;
        }
    };
    handleSelectBotAdmin = async (newValue) => {
        try {
            const selectedChat = selectedChatStore.get('selectedChat');
            const selectedChatType = selectedChat ? selectedChat.type : '';
            const type = selectedChatType === 'group' ? 'group' : 'user';
            const user = userStore.get('user');
            const context = newValue === 'admin' ? 'contactadmin' : '';
            const userResponse = await updateUser({
                type,
                channel: user.channel,
                id: user.id,
                context
            });
            if (['user-updated', 'group-updated'].includes(userResponse.code)) {
                this.selectedValue = newValue;
                userStore.set('user', {
                    ...userStore.get('user'),
                    context
                });
                persistUser(user.channel, user.id, userStore.get('user'));
            }
        }
        catch (error) {
            handleError(error, 'Failed to SelectBotAdmin');
        }
    };
    render() {
        const t = useTranslation();
        const selectedChat = selectedChatStore.get('selectedChat');
        const channel = selectedChat ? selectedChat.channel : '';
        const platformColor = channel === 'line' ? 'text-green-500' : 'text-blue-500';
        const isFbOrIgStandalone = ['facebook', 'instagram'].includes(channel);
        if (!selectedChat)
            return null;
        const connection = configStore.get('connectionList').find(connection => connection.type === 'zwiz' && connection.channels?.find(channel => channel.id === selectedChat?.connection?.id));
        const mode = deviceModeStore.get('mode');
        const isMobile = mode === 'mobile';
        const zwizSyncMessage = String(configStore.get('zwizSyncMessage')) === 'true';
        const menuItems = [
            ...(mode === 'desktop' ? [] : [{ label: t('chat_header.view_profile'), value: 'profile', onClick: this.handleShowProfile }]),
            ...(selectedChat.connection?.type === 'zwiz'
                && connection.type === 'zwiz'
                && connection.platform === 'enterprise'
                ? [{ label: t('ticket'), value: 'ticket', onClick: this.handleShowProfileTicket }]
                : []),
            ...(isMobile
                ? [
                    { label: this.isPin ? t('chat_header.unpin') : t('chat_header.pin'), value: 'pin', onClick: this.handleTogglePinChatClick },
                    { label: this.isSpam ? t('chat_header.not_spam') : t('chat_header.spam'), value: 'spam', onClick: this.handleToggleSpamChatClick },
                    { label: this.isUnRead ? t('chat_header.read') : t('chat_header.unread'), value: 'read', onClick: this.handleToggleReadMessageClick },
                ]
                : []),
            ...(isFbOrIgStandalone
                ? [
                    ...((selectedChat.connection?.type === 'zwiz' ? zwizSyncMessage : true)
                        ? [{ label: t('chat_header.sync_history'), value: 'sync_message', onClick: this.handleSyncChatMessage }]
                        : []),
                    ...(selectedChat && selectedChat.channel === 'facebook' ? [{ label: t('chat_header.sync_tags'), value: 'sync_tags', onClick: this.handleSyncTags }] : []),
                ]
                : []),
        ];
        return (h(Host, null, h("div", { class: "chat-header scroll-container" }, h("div", { class: "chat-header-avatar-wrapper", onClick: this.handleShowProfile }, isMobile && h(ZIconButton, { variant: "none", iconName: "ChevronLeft", onClick: this.handleBackToChatList }), h("div", { class: "relative" }, h("z-avatar", { pictureUrl: getChatPicture(selectedChat), size: "small" }), selectedChat.type === 'group' && (h("div", { class: "chat-header-avatar-badge" }, h(ZAvatarGroup, { size: "x-small" })))), h("div", { class: "chat-header-info" }, h("div", { class: "chat-header-name" }, getChatName(selectedChat)), h("div", { class: "chat-header-connection-wrapper" }, selectedChat && selectedChat.connection.type === 'zwiz' && (h("img", { src: "https://zwizai-platform.s3.ap-southeast-1.amazonaws.com/zignal-package/zwiz.png", alt: "agent avatar zwiz", class: "chat-header-connection-icon", loading: "lazy" })), h("img", { src: getChatChannelPictureUrl(selectedChat), alt: "agent avatar", class: "chat-header-connection-icon", loading: "lazy" }), h("span", { class: `chat-header-connection-text ${platformColor}` }, selectedChat ? selectedChat.connection.name : '')))), h("div", { class: "chat-header-toolbar-wrapper" }, !isMobile && (h(Fragment, null, h(ZIconButton, { variant: "none", iconName: "Pin", addClassIcon: this.isPin ? 'rotate-45 size-5 text-primary' : 'size-5', isLoading: this.isPinLoading, onClick: this.handleTogglePinChatClick, title: this.isPin ? t('chat_header.unpin') : t('chat_header.pin'), disabled: this.isSpamLoading }), h(ZIconButton, { variant: "none", iconName: this.isSpam ? 'CircleOff' : 'Ban', addClassIcon: this.isSpam ? 'text-primary' : '', isLoading: this.isSpamLoading, onClick: this.handleToggleSpamChatClick, title: this.isSpam ? t('chat_header.not_spam') : t('chat_header.spam'), disabled: this.isPinLoading }), h(ZIconButton, { variant: "none", iconName: this.isUnRead ? 'MailCheck' : 'Mail', addClassIcon: this.isUnRead ? 'text-primary' : '', isLoading: this.isReadLoading, onClick: this.handleToggleReadMessageClick, title: this.isUnRead ? t('chat_header.read') : t('chat_header.unread') }))), h(ZIconButton, { variant: "none", iconName: 'Search', onClick: this.handleSearchMessageClick, title: t('chat_header.search') }), selectedChat && connection && connection?.type === 'zwiz' && connection?.platform === 'sme' && (h(ZToggle, { value: this.selectedValue, onChange: this.handleSelectBotAdmin, title: this.selectedValue === 'bot' ? t('on') : t('off') })), menuItems.length > 0 && (h("menu-list", { referenceSelector: "chat-header-menu", iconName: "Ellipsis", position: "bottom-end", menuItems: menuItems, variant: "none" }))))));
    }
    static get is() { return "chat-header"; }
    static get originalStyleUrls() {
        return {
            "$": ["chat-header.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["chat-header.css"]
        };
    }
    static get states() {
        return {
            "isPinLoading": {},
            "isSpamLoading": {},
            "isReadLoading": {},
            "isPin": {},
            "isSpam": {},
            "isUnRead": {},
            "selectedValue": {}
        };
    }
}
