import { Host, h } from "@stencil/core";
import { computePosition, autoUpdate, flip, shift } from "@floating-ui/dom";
import { ZButton } from "../internal-component/z-button";
import { Icon } from "../internal-component/icon";
import { configStore, filterChatsStore, chatsStore } from "../../store/store";
import { useTranslation } from "../../utils/utils";
import { formatFilterConnection } from "../../store/chat";
export class MenuChatChannel {
    referenceSelector;
    isOpen = false;
    internalLoading = false;
    triggerEl;
    popperEl;
    cleanup;
    componentWillLoad() {
        const filterChat = filterChatsStore.get('filterChat');
        if (!filterChat || !filterChat.connections) {
            const allValues = configStore.get('connectionList').flatMap(connection => connection.type === 'zwiz'
                ? connection.channels?.map(channel => channel.id) ?? []
                : [connection.id]);
            this.handleSetFilterConnection(allValues);
        }
    }
    disposeStore;
    componentDidLoad() {
        document.addEventListener('click', this.handleClickOutside);
        window.addEventListener('close-all-poppers', this.handleCloseOthers);
        this.disposeStore = chatsStore.onChange('loading', loading => {
            if (!loading) {
                this.internalLoading = false;
            }
        });
    }
    disconnectedCallback() {
        document.removeEventListener('click', this.handleClickOutside);
        window.removeEventListener('close-all-poppers', this.handleCloseOthers);
        if (this.cleanup)
            this.cleanup();
        if (this.disposeStore)
            this.disposeStore();
        if (this.popperEl)
            this.popperEl.remove();
    }
    handleClickOutside = (e) => {
        const path = e.composedPath();
        if (!path.includes(this.triggerEl) && !path.includes(this.popperEl)) {
            this.isOpen = false;
            if (this.cleanup)
                this.cleanup();
            if (this.popperEl)
                this.popperEl.remove();
        }
    };
    handleCloseOthers = (e) => {
        if (e.detail !== this && this.isOpen) {
            this.isOpen = false;
            if (this.cleanup)
                this.cleanup();
            if (this.popperEl)
                this.popperEl.remove();
        }
    };
    async toggleMenu() {
        this.isOpen = !this.isOpen;
        if (this.isOpen) {
            window.dispatchEvent(new CustomEvent('close-all-poppers', { detail: this }));
            const referenceEl = document.getElementById(this.referenceSelector);
            if (!referenceEl || !this.popperEl)
                return;
            const container = document.getElementById('chat-panel');
            container.appendChild(this.popperEl);
            this.cleanup = autoUpdate(referenceEl, this.popperEl, () => {
                computePosition(referenceEl, this.popperEl, {
                    placement: 'bottom-start',
                    middleware: [flip(), shift()],
                }).then(({ x, y }) => {
                    Object.assign(this.popperEl.style, {
                        left: `${x}px`,
                        top: `${y}px`,
                        zIndex: '9999',
                    });
                });
            });
        }
        else {
            if (this.cleanup)
                this.cleanup();
            if (this.popperEl)
                this.popperEl.remove();
        }
    }
    handleSetFilterConnection = (selectedArray) => {
        this.internalLoading = true;
        let connections = [];
        const filterChats = filterChatsStore.get('filterChat') || {};
        const openChatByFilter = configStore.get('openChatByFilter');
        if (openChatByFilter) {
            Object.assign(filterChats, { userIds: [...(filterChats?.userIds || []), openChatByFilter.user_id] });
            if (openChatByFilter.connection_id && openChatByFilter.channel) {
                connections = [{
                        id: openChatByFilter.connection_id,
                        channel: [openChatByFilter.channel],
                        isOpenChatByFilter: true
                    }];
            }
        }
        else {
            connections = formatFilterConnection(selectedArray);
        }
        // Trrigger load chats by filterChat
        filterChatsStore.set('filterChat', {
            ...filterChats,
            connections,
        });
    };
    render() {
        const t = useTranslation();
        const filterChat = filterChatsStore.get('filterChat');
        const filterCount = filterChat ? (filterChat.connections ? filterChat.connections.length : 0) : 0;
        const label = t('channel'); //`${t('channel')} ${filterCount > 0 ? `(${filterCount > 9 ? '9+' : filterCount})` : ''}`;
        const allValues = configStore.get('connectionList').flatMap(connection => connection.type === 'zwiz'
            ? connection.channels?.map(channel => channel.id) ?? []
            : [connection.id]);
        const computedSelected = (!filterChat || !filterChat.connections)
            ? new Set(allValues)
            : new Set(filterChat.connections.map(c => c.id));
        return (h(Host, { key: '192d9dbc65f58283a0de142f5e4c59694781489b' }, h("div", { key: '4ac2afe423a3be24a39ce037c220d80e1b8c3223', class: "relative" }, h(ZButton, { key: '1bfd44628032566edfd4ac98cea7875b0c405008', size: "small", padding: "px-4 py-1.5", fullWidth: true, variant: filterCount > 0 ? 'primary' : 'outlined', disabled: chatsStore.get('loading') && this.internalLoading, startIcon: this.internalLoading && chatsStore.get('loading') ? (h(Icon, { name: "LoaderCircle", addClass: "size-4 animate-spin" })) : (h(Icon, { name: 'Globe', addClass: "size-4" })), endIcon: h(Icon, { name: 'Triangle', addClass: "menu-chat-channel-icon" }), label: filterCount > 0 ? label : undefined, title: label, onClick: event => {
                event.stopPropagation();
                this.toggleMenu();
            }, ref: el => (this.triggerEl = el), id: this.referenceSelector }), h("div", { key: '8bd4d389d8323b78646456c7d118000509f18fb2', ref: el => (this.popperEl = el), class: `menu-chat-channel-wrapper ${this.isOpen ? '' : 'hidden!'}` }, h("div", { key: 'd2feaf09470fc12b12d2f304ff324ea4048824bb', class: "menu-chat-channel-item-wrapper" }, h("checkbox-list", { key: '49d988b7df04e2d1fb40a668cf33fc534af11366', selected: computedSelected, itemList: configStore.get('connectionList').flatMap(connection => (connection.type === 'zwiz'
                ? (connection.channels || []).map(channel => ({
                    iconName: connection.type,
                    subIconName: channel.channel,
                    label: channel.channel_name,
                    value: channel.id,
                }))
                : [{
                        iconName: connection.type,
                        subIconName: undefined,
                        label: connection.name,
                        value: connection.id,
                    }])), onCheckbox: event => this.handleSetFilterConnection(event.detail) }))))));
    }
    static get is() { return "menu-chat-channel"; }
    static get originalStyleUrls() {
        return {
            "$": ["menu-chat-channel.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["menu-chat-channel.css"]
        };
    }
    static get properties() {
        return {
            "referenceSelector": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "reference-selector"
            }
        };
    }
    static get states() {
        return {
            "isOpen": {},
            "internalLoading": {}
        };
    }
}
