import { Host, h, Fragment } from "@stencil/core";
import { Icon } from "../internal-component/icon";
import { deviceModeStore, profilePanelStore, selectedChatStore, translateStore } from "../../store/store";
import { ZIconButton } from "../internal-component/z-icon-button";
import { searchChats } from "../../api";
import { SEARCH_CHAT_MESSAGE_PAGE_LIMIT } from "../../utils/constant";
import { getChatChannelPictureUrl, getChatName, getChatPicture, getChatUserInfo, handleGetChat } from "../../store/chat";
import { handleError } from "../../store/dialog";
import { leaveRoom } from "../../utils/socket";
import { ZAvatarGroup } from "../internal-component/z-avatar-group";
import { getConnectionItem } from "../../utils/func";
import { useTranslation } from "../../utils/utils";
export class DialogSearchChatUser {
    initialQuery;
    close;
    query = '';
    latestSearch = '';
    searchUserState = 'initial';
    searchChatState = 'initial';
    isLoadingUser = false;
    isLoadingChat = false;
    userResults = [];
    chatResults = [];
    totalUserPage = 0;
    totalChatPage = 0;
    currentUserPage = 1;
    currentChatPage = 1;
    componentWillLoad() {
        if (this.initialQuery) {
            this.query = this.initialQuery;
        }
    }
    async componentDidLoad() {
        const inputRef = document.getElementById('search-chat-user');
        inputRef.focus();
        await this.handleInitialSearch();
    }
    async handleInitialSearch() {
        if (!this.query)
            return;
        await Promise.all([
            this.handleSearch(this.query, 'chat'),
            this.handleSearch(this.query, 'user')
        ]);
    }
    async handleSearch(value, type, page) {
        try {
            if (type === 'user') {
                this.isLoadingUser = true;
                this.searchUserState = 'searching';
            }
            else {
                this.isLoadingChat = true;
                this.searchChatState = 'searching';
            }
            const { chats, total } = await searchChats({
                search: value,
                type,
                page,
                limit: SEARCH_CHAT_MESSAGE_PAGE_LIMIT
            });
            const isInitialPage = !page || page === 1;
            switch (type) {
                case 'chat':
                    this.chatResults = chats;
                    if (isInitialPage) {
                        this.currentChatPage = 1;
                        this.totalChatPage = Math.ceil(total / SEARCH_CHAT_MESSAGE_PAGE_LIMIT);
                    }
                    break;
                case 'user':
                    this.userResults = chats;
                    if (isInitialPage) {
                        this.currentUserPage = 1;
                        this.totalUserPage = Math.ceil(total / SEARCH_CHAT_MESSAGE_PAGE_LIMIT);
                    }
                    break;
            }
            if (isInitialPage) {
                this.latestSearch = value;
            }
        }
        catch (error) {
            handleError(error, `Failed to search chat user : ${type}`);
        }
        finally {
            if (type === 'user') {
                this.isLoadingUser = false;
                this.searchUserState = 'finished';
            }
            else {
                this.isLoadingChat = false;
                this.searchChatState = 'finished';
            }
        }
    }
    handleInput = (e) => {
        const value = e.target.value;
        this.query = value;
    };
    handleClose = () => {
        this.close.emit();
    };
    handleUserPageChange = (event) => {
        this.currentUserPage = event.detail;
        this.handleSearch(this.latestSearch, 'user', this.currentUserPage);
    };
    handleChatPageChange = (event) => {
        this.currentChatPage = event.detail;
        this.handleSearch(this.latestSearch, 'chat', this.currentChatPage);
    };
    handleSelectUser = async (sessionId) => {
        try {
            this.isLoadingUser = true;
            const selectedChat = selectedChatStore.get('selectedChat');
            if (selectedChat && selectedChat.id !== sessionId) {
                leaveRoom(selectedChat.id);
            }
            const chat = await handleGetChat(sessionId);
            selectedChatStore.set('selectedChat', chat);
            profilePanelStore.reset();
            translateStore.reset();
            this.close.emit();
        }
        catch (error) {
            handleError(error, 'Failed to jump Chat from select user');
        }
        finally {
            this.isLoadingUser = false;
        }
    };
    handleSelectChat = async (sessionId) => {
        try {
            this.isLoadingChat = true;
            const selectedChat = selectedChatStore.get('selectedChat');
            if (selectedChat && selectedChat.id !== sessionId) {
                leaveRoom(selectedChat.id);
            }
            const chat = await handleGetChat(sessionId);
            selectedChatStore.set('selectedChat', chat);
            selectedChatStore.set('isSearchMessage', true);
            selectedChatStore.set('initialSearchMessage', this.latestSearch);
            profilePanelStore.reset();
            translateStore.reset();
            this.close.emit();
        }
        catch (error) {
            handleError(error, 'Failed to jump Chat from select chat');
        }
        finally {
            this.isLoadingChat = false;
        }
    };
    renderUserItem = (user) => {
        const channel = user ? user.channel : '';
        const platformColor = channel === 'line' ? 'text-green-500' : 'text-blue-500';
        const highlightText = (text) => {
            if (!this.latestSearch)
                return text;
            const parts = text.split(new RegExp(`(${this.latestSearch})`, 'gi'));
            return parts.map(part => part.toLowerCase() === this.latestSearch.toLowerCase()
                ? h("span", { class: "text-primary" }, part)
                : part);
        };
        const name = getChatName(user);
        const email = getChatUserInfo({ ...user, field: 'email' });
        const phoneNumber = getChatUserInfo({ ...user, field: 'phone_number' });
        const note = getChatUserInfo({ ...user, field: 'note' });
        const hasMatch = (text) => {
            if (!this.latestSearch || !text)
                return false;
            const regex = new RegExp(this.latestSearch, 'gi');
            return regex.test(text);
        };
        return (h("div", { class: "search-item", onClick: () => this.handleSelectUser(user.id) }, h("div", { class: "search-item-avatar" }, h("z-avatar", { pictureUrl: getChatPicture(user), size: "small" }), user.type === 'group' &&
            h("div", { class: "search-item-avatar-badge" }, h(ZAvatarGroup, { size: "x-small" }))), h("div", { class: "search-item-content" }, h("div", { class: "search-item-header" }, h("div", { class: "search-item-result-connection-wrapper" }, user.connection.type === 'zwiz' &&
            h("img", { src: "https://zwizai-platform.s3.ap-southeast-1.amazonaws.com/zignal-package/zwiz.png", alt: "agent avatar zwiz", class: "search-item-result-connection-icon", loading: "lazy" }), h("img", { src: getChatChannelPictureUrl(user), alt: "agent avatar", class: "search-item-result-connection-icon", loading: "lazy" }), h("span", { class: `search-item-result-connection-text ${platformColor}` }, user ? user.connection.name : ''))), h("div", { class: "search-item-name" }, highlightText(name)), email && hasMatch(email) &&
            h("div", { class: "search-item-detail" }, "\u0E2D\u0E35\u0E40\u0E21\u0E25 : ", highlightText(email)), phoneNumber && hasMatch(phoneNumber) &&
            h("div", { class: "search-item-detail" }, "\u0E40\u0E1A\u0E2D\u0E23\u0E4C : ", highlightText(phoneNumber)), note && hasMatch(note) &&
            h("div", { class: "search-item-detail" }, "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E2B\u0E15\u0E38 : ", highlightText(note))), h(ZIconButton, { variant: "none", iconName: "MessageSquareText", addClassIcon: "size-5 text-primary", noPaddingY: true })));
    };
    renderChatItem = (chat) => {
        const channel = chat ? chat.channel : '';
        const platformColor = channel === 'line' ? 'text-green-500' : 'text-blue-500';
        const numberFormatter = Intl.NumberFormat();
        const connectionItem = getConnectionItem(chat);
        const isLocked = connectionItem?.is_locked || false;
        return (h("div", { class: "search-item", onClick: () => {
                if (isLocked)
                    return;
                this.handleSelectChat(chat.id);
            } }, h("div", { class: "search-item-avatar" }, h("z-avatar", { pictureUrl: getChatPicture(chat), size: "small" }), chat.type === 'group' &&
            h("div", { class: "search-item-avatar-badge" }, h(ZAvatarGroup, { size: "x-small" }))), h("div", { class: "search-item-content" }, h("div", { class: "search-item-header" }, h("div", { class: "search-item-result-connection-wrapper" }, chat.connection.type === 'zwiz' &&
            h("img", { src: "https://zwizai-platform.s3.ap-southeast-1.amazonaws.com/zignal-package/zwiz.png", alt: "agent avatar zwiz", class: "search-item-result-connection-icon", loading: "lazy" }), h("img", { src: getChatChannelPictureUrl(chat), alt: "agent avatar", class: "search-item-result-connection-icon", loading: "lazy" }), h("span", { class: `search-item-result-connection-text ${platformColor}` }, chat ? chat.connection.name : ''))), h("div", { class: "search-item-name" }, getChatName(chat)), h("div", { class: "search-item-detail" }, numberFormatter.format(chat.result_messages.length), " \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21")), h(ZIconButton, { variant: "none", iconName: "MessageSquareText", addClassIcon: "size-5 text-primary", noPaddingY: true }), isLocked && (h("div", { class: "search-item-locked" }))));
    };
    render() {
        const t = useTranslation();
        return (h(Host, { key: '8c4736e53f698e422395e951a3074f1b13d27b50' }, h("div", { key: '70d3f5badacb8afe48e14f4a26605f43fd2c5bf5', class: `dialog-wrapper ${deviceModeStore.get('mode') === 'mobile' ? 'w-xs' : 'min-w-md w-xl'}` }, h("div", { key: '15b370ef39cb58c756b8de9cc859838b5813acef', class: "dialog-header" }, h("h2", { key: '514513945d687ef31d92c3c5c7a2f0f0dd917014', class: "dialog-title" }, t('search')), h("div", { key: '577625289882690654f28683160c90e919c4068e', class: "dialog-close" }, h(ZIconButton, { key: 'd54c880f1b2d236ef69c05ea883f639f7d9c7803', iconName: "X", variant: "none", onClick: this.handleClose }))), h("div", { key: 'f046751cd74cffa4357fb8d92b1938d3a5f85e5f', class: "px-4" }, h("div", { key: '3b5977a9f202e5930100dff94d3049b451f4fa66', class: "dialog-search-input" }, h("input", { key: 'a0ff9b32e650a17701ba188bf883dc39513517a1', id: "search-chat-user", type: "text", placeholder: t('chat_tab.search_chat'), class: "search-input", value: this.query, onInput: this.handleInput, onKeyDown: (e) => e.key === 'Enter' && this.handleInitialSearch() }), h("button", { key: '64813665ec083db90d48d85f4ea537d46ea15d60', class: "search-button", onClick: () => this.handleInitialSearch() }, h(Icon, { key: '3d810e59101291bcf4dbce2247b6b94529013fba', name: "Search" })))), this.searchUserState === 'finished' &&
            this.searchChatState === 'finished' &&
            h("span", { key: '7d903f53559d2e5dd5e2969f9ad990a08c2b67b4', class: "search-result-text" }, t('search_result'), "\u00A0\"", this.latestSearch, "\"\u00A0"), h("div", { key: 'c557d9498e6ae2ef8ffaf5793dad3fe4fa0120da', class: "search-divider" }), h("div", { key: 'b587a2a81cd808ade685634a67af0c774dcaabd2', class: "dialog-content-chat-user scroll-container" }, h("div", { key: '22ef6e76578e15eb44ff7cbd2845ceb30fae7d5d', class: "search-section" }, h("h3", { key: 'd3a3c11e2c51d43c949c80f55087e228613e91a5', class: "section-title" }, t('background_job.user')), h("div", { key: '36a45bf019107cb775a89e94949996e3109136de', class: `search-results ${(this.userResults.length > 0 && !this.isLoadingUser) ? '' : 'search-results-empty'}` }, this.isLoadingUser
            ? h("div", { class: "search-item-loading" }, h(Icon, { name: "LoaderCircle", addClass: "animate-spin size-6" }))
            : h(Fragment, null, this.userResults.length > 0
                ? this.userResults.map(user => this.renderUserItem(user))
                : h("div", { class: "search-results-empty-message" }, t('user_not_found')))), this.totalUserPage > 1 && (h("div", { key: '4062224153595101d9293f018aa3235b87424c4d', class: "pagination-wrapper" }, h("z-pagination", { key: '03dc1241666787d95aa6405e1bb32f90acb3e06a', currentPage: this.currentUserPage, totalPages: this.totalUserPage, onPageChange: this.handleUserPageChange })))), h("div", { key: '30e07133f0dcd7a82c51741fd13f4683ea469cae', class: "search-section" }, h("h3", { key: 'd3615f1cbdaf52ce79e3680d77b1e9beed00a08e', class: "section-title" }, t('chat_tab.chat')), h("div", { key: '16982581607557f52b37054355adacbb016f6e7e', class: `search-results ${(this.chatResults.length > 0 && !this.isLoadingChat) ? '' : 'search-results-empty'}` }, this.isLoadingChat
            ? h("div", { class: "search-item-loading" }, h(Icon, { name: "LoaderCircle", addClass: "animate-spin size-6" }))
            : h(Fragment, null, this.chatResults.length > 0
                ? this.chatResults.map(chat => this.renderChatItem(chat))
                : h("div", { class: "search-results-empty-message" }, t('chat_tab.chat_not_found')))), this.totalChatPage > 1 && (h("div", { key: '07b32ef01faf7aa7067abe8788b3064664823048', class: "pagination-wrapper" }, h("z-pagination", { key: '578b7b8eeda51f478ca8c484fe1a930717098cc5', currentPage: this.currentChatPage, totalPages: this.totalChatPage, onPageChange: this.handleChatPageChange }))))))));
    }
    static get is() { return "dialog-search-chat-user"; }
    static get originalStyleUrls() {
        return {
            "$": ["dialog-search-chat-user.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["dialog-search-chat-user.css"]
        };
    }
    static get properties() {
        return {
            "initialQuery": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "initial-query"
            }
        };
    }
    static get states() {
        return {
            "query": {},
            "latestSearch": {},
            "searchUserState": {},
            "searchChatState": {},
            "isLoadingUser": {},
            "isLoadingChat": {},
            "userResults": {},
            "chatResults": {},
            "totalUserPage": {},
            "totalChatPage": {},
            "currentUserPage": {},
            "currentChatPage": {}
        };
    }
    static get events() {
        return [{
                "method": "close",
                "name": "close",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
}
