import { Host, h, Fragment } from "@stencil/core";
import { Icon } from "../internal-component/icon";
import { messagesStore, selectedChatStore } from "../../store/store";
import { searchChatMessages } from "../../api";
import { handleError } from "../../store/dialog";
import { clearHighlight, handleGetChatMessages, scrollToMessage } from "../../store/message";
import { ZIconButton } from "../internal-component/z-icon-button";
export class SearchMessage {
    disposeListener;
    query = '';
    viewIndex = 0;
    isLoading = false;
    searchState = 'initial';
    latestSearch = '';
    searchResultMessages = [];
    async componentWillLoad() {
        const initialValue = selectedChatStore.get('initialSearchMessage');
        if (initialValue) {
            this.query = initialValue;
            setTimeout(() => this.handleSearch(initialValue), 100);
        }
        this.disposeListener = selectedChatStore.onChange('initialSearchMessage', async (newInitialSearchMessage) => {
            if (newInitialSearchMessage) {
                this.query = newInitialSearchMessage;
                await this.handleSearch(newInitialSearchMessage);
            }
        });
    }
    inputElement;
    componentDidLoad() {
        requestAnimationFrame(() => {
            if (this.inputElement) {
                this.inputElement.focus();
            }
        });
    }
    disconnectedCallback() {
        if (this.disposeListener)
            this.disposeListener();
    }
    handleInput = (e) => {
        const value = e.target.value;
        this.query = value;
    };
    handleSearch = async (value) => {
        clearHighlight();
        const valueTrim = value ? value.trim() : '';
        const _search = valueTrim.length > 0 ? valueTrim : undefined;
        if (!_search)
            return;
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat.id)
            return;
        try {
            this.isLoading = true;
            this.searchState = 'searching';
            const { messages } = await searchChatMessages({
                sessionId: selectedChat.id,
                search: _search
            });
            this.searchResultMessages = messages;
            if (this.searchResultMessages.length > 0) {
                const messageId = this.searchResultMessages[0].id;
                await this.handleJumpToMessage(messageId, _search);
            }
            this.latestSearch = _search;
        }
        catch (error) {
            handleError(error, 'Failed to search message');
        }
        finally {
            this.viewIndex = 0;
            this.isLoading = false;
            this.searchState = 'finished';
        }
    };
    handleJumpToMessage = async (messageId, search) => {
        const isSuccessScroll = scrollToMessage({ messageId, focus: false, highlight: true, search });
        if (!isSuccessScroll) {
            try {
                this.isLoading = true;
                await handleGetChatMessages({ startMessageId: messageId });
                setTimeout(() => {
                    const isSuccessScroll = scrollToMessage({ messageId, focus: false, highlight: true, search });
                    if (isSuccessScroll) {
                        setTimeout(() => {
                            messagesStore.set('jumpMessageId', undefined);
                        }, 300);
                    }
                }, 500);
            }
            catch (error) {
                handleError(error, 'Failed to scroll to message');
            }
            finally {
                this.isLoading = false;
            }
        }
    };
    handleEnter = (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            this.handleSearch(this.query);
        }
    };
    handleClick = () => {
        this.handleSearch(this.query);
    };
    handleClose = () => {
        selectedChatStore.set('isSearchMessage', false);
        clearHighlight();
    };
    handleNext = async () => {
        if (this.viewIndex < (this.searchResultMessages.length - 1)) {
            this.viewIndex++;
        }
        const messageId = this.searchResultMessages[this.viewIndex].id;
        await this.handleJumpToMessage(messageId, this.query);
    };
    handlePrev = async () => {
        if (this.viewIndex > 0) {
            this.viewIndex--;
        }
        const messageId = this.searchResultMessages[this.viewIndex].id;
        await this.handleJumpToMessage(messageId, this.query);
    };
    render() {
        return (h(Host, { key: '7599a8db13cfdbeec903fa4b708dd855704deca0' }, h("div", { key: 'ca49ff49b9942fda98acacbaca6f85a7115caeb0', class: "search-message-box-input-wrapper" }, h("div", { key: 'baad42aa80f286b869dd8f3d53c0926117de11cd', class: "search-message-box-input-box" }, h("input", { key: 'e4a71c0d625d51f2c005569edb33e9c3251180c7', id: "search-message", ref: (el) => this.inputElement = el, type: "text", placeholder: "\u0E04\u0E49\u0E19\u0E2B\u0E32\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21", class: "search-message-box-input", value: this.query, onInput: this.handleInput, onKeyDown: this.handleEnter }), h("div", { key: 'bef3b2608fe390831fe025d9bf76ca27cb1a2204', class: "flex-1" }, h(ZIconButton, { key: '3becdc07d7a56ff0e80a76976c781e5488525e62', iconName: "Search", onClick: this.handleClick })), h("div", { key: 'af8bb9f7e102109f35bc2a4ea2a8eafb08f5b135', class: "flex-1" }, h(ZIconButton, { key: 'c8e96fda43ce4e56865909c2a89e35065203ed3d', variant: "text", iconName: "X", onClick: this.handleClose }))), this.searchState !== 'initial' &&
            h("div", { key: '1804d92797b4e07b5e8b7668abe379422793941e', class: "search-message-box-detail-box" }, this.isLoading
                ? h("div", { class: "search-message-box-input-icon-navigate" }, h(Icon, { name: "LoaderCircle", addClass: "animate-spin size-4" }))
                : h(Fragment, null, h("span", { class: "text-xs text-surface" }, "\u0E1C\u0E25\u0E01\u0E32\u0E23\u0E04\u0E49\u0E19\u0E2B\u0E32 \"", this.latestSearch, "\"\u00A0", this.searchResultMessages.length === 0
                    ? 'ไม่พบข้อความ'
                    : `${this.viewIndex + 1}/${this.searchResultMessages.length} ข้อความ`), this.searchResultMessages.length > 0 &&
                    h(Fragment, null, h("div", { class: "search-message-box-input-icon-navigate", onClick: this.handleNext }, h(Icon, { name: "ChevronUp" })), h("div", { class: "search-message-box-input-icon-navigate", onClick: this.handlePrev }, h(Icon, { name: "ChevronDown" }))))))));
    }
    static get is() { return "search-message"; }
    static get originalStyleUrls() {
        return {
            "$": ["search-message.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["search-message.css"]
        };
    }
    static get states() {
        return {
            "query": {},
            "viewIndex": {},
            "isLoading": {},
            "searchState": {},
            "latestSearch": {},
            "searchResultMessages": {}
        };
    }
}
