import { Host, h, Fragment } from "@stencil/core";
import { computePosition, autoUpdate, offset, flip, shift } from "@floating-ui/dom";
import { ZTagOrStatusItem } from "../internal-component/z-tag-or-status-item";
import { useTranslation } from "../../utils/utils";
import { Icon } from "../internal-component/icon";
import { GET_USER_TAG_PAGE_LIMIT } from "../../utils/constant";
export class AutocompleteMultipleSelect {
    fetchItems;
    selectedIds = [];
    referenceSelector;
    showClearButton = false;
    showSelectAllButton = false;
    selecting;
    allItems = [];
    filteredItems = [];
    inputValue = '';
    showDropdown = false;
    loading = true;
    selectedItems = [];
    triggerEl;
    popperEl;
    cleanup;
    totalItems = -1;
    offset = 0;
    limit = GET_USER_TAG_PAGE_LIMIT;
    isBackendPaginated = false;
    searchTimeout;
    async componentWillLoad() {
        await this.loadItems(true);
        this.selectedItems = this.selectedIds;
    }
    async loadItems(reset = false) {
        if (reset) {
            this.offset = 0;
            this.allItems = [];
            this.filteredItems = [];
            this.totalItems = -1;
        }
        this.loading = true;
        try {
            const fetchParams = { limit: this.limit, offset: this.offset };
            if (this.inputValue) {
                fetchParams.search = this.inputValue;
            }
            const response = await this.fetchItems(fetchParams);
            let items = [];
            if (Array.isArray(response)) {
                items = response;
                this.isBackendPaginated = false;
            }
            else if (response) {
                if (response.tags)
                    items = response.tags;
                else if (response.statuses)
                    items = response.statuses;
                else if (response.items)
                    items = response.items;
                else
                    items = Array.isArray(response) ? response : [];
                if (response.total !== undefined) {
                    this.isBackendPaginated = true;
                    this.totalItems = response.total;
                }
                else {
                    this.isBackendPaginated = false;
                    this.totalItems = items.length;
                }
            }
            // Filter out duplicate IDs
            const newItems = items.filter(item => !this.allItems.some(existing => existing.id === item.id));
            this.allItems = [...this.allItems, ...newItems];
            if (this.isBackendPaginated) {
                this.filteredItems = this.allItems;
            }
            else {
                this.filteredItems = this.allItems.filter(i => i.name.toLowerCase().includes(this.inputValue.toLowerCase()));
            }
        }
        catch (e) {
            console.error(e);
        }
        this.loading = false;
    }
    componentDidLoad() {
        document.addEventListener('click', this.handleClickOutside);
        window.addEventListener('close-all-poppers', this.handleCloseOthers);
    }
    disconnectedCallback() {
        document.removeEventListener('click', this.handleClickOutside);
        window.removeEventListener('close-all-poppers', this.handleCloseOthers);
        if (this.cleanup)
            this.cleanup();
        if (this.popperEl)
            this.popperEl.remove();
    }
    handleClickOutside = (e) => {
        const path = e.composedPath();
        if (!path.includes(this.triggerEl) && !path.includes(this.popperEl)) {
            this.showDropdown = false;
            if (this.cleanup)
                this.cleanup();
            if (this.popperEl)
                this.popperEl.remove();
        }
    };
    handleCloseOthers = (e) => {
        if (e.detail !== this && this.showDropdown) {
            this.showDropdown = false;
            if (this.cleanup)
                this.cleanup();
            if (this.popperEl)
                this.popperEl.remove();
        }
    };
    onInput = (e) => {
        const value = e.target.value;
        this.inputValue = value;
        this.showDropdown = true;
        if (this.isBackendPaginated) {
            if (this.searchTimeout)
                clearTimeout(this.searchTimeout);
            this.searchTimeout = setTimeout(() => {
                this.loadItems(true);
            }, 300);
        }
        else {
            this.filteredItems = this.allItems.filter(i => i.name.toLowerCase().includes(value.toLowerCase()));
        }
    };
    onSelectItem = (item) => {
        if (!this.selectedItems.includes(item.id)) {
            this.selectedItems = [...this.selectedItems, item.id];
            this.selecting.emit(this.selectedItems);
        }
        this.inputValue = '';
        this.showDropdown = false;
    };
    removeChip = (id) => {
        this.selectedItems = this.selectedItems.filter(sid => sid !== id);
        this.selecting.emit(this.selectedItems);
    };
    onClearItem() {
        this.selectedItems = [];
        this.selecting.emit(this.selectedItems);
    }
    onSelectAll = () => {
        const idsToSelect = this.filteredItems.map(item => item.id).filter((id) => !!id);
        const newSelectedItems = Array.from(new Set([...this.selectedItems, ...idsToSelect]));
        this.selectedItems = newSelectedItems;
        this.selecting.emit(this.selectedItems);
        this.inputValue = '';
        this.showDropdown = false;
    };
    handleDropdownChange(newValue) {
        if (newValue) {
            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-app');
            if (container) {
                container.appendChild(this.popperEl);
            }
            this.cleanup = autoUpdate(referenceEl, this.popperEl, () => {
                computePosition(referenceEl, this.popperEl, {
                    placement: 'bottom-start',
                    middleware: [offset(4), flip(), shift()],
                }).then(({ x, y }) => {
                    Object.assign(this.popperEl.style, {
                        width: `${referenceEl.offsetWidth}px`,
                        left: `${x}px`,
                        top: `${y}px`,
                        zIndex: '9999',
                    });
                });
            });
        }
        else {
            if (this.cleanup) {
                this.cleanup();
                this.cleanup = undefined;
            }
            if (this.popperEl) {
                this.popperEl.remove();
            }
        }
    }
    onFocus = () => {
        this.showDropdown = true;
    };
    toggleDropdown = (e) => {
        e.stopPropagation();
        this.showDropdown = !this.showDropdown;
    };
    handleScroll = (e) => {
        const el = e.target;
        if (el.scrollHeight - el.scrollTop - el.clientHeight < 50 && !this.loading) {
            if (this.isBackendPaginated && (this.totalItems === -1 || this.allItems.length < this.totalItems)) {
                this.offset += this.limit;
                this.loadItems(false);
            }
        }
    };
    render() {
        const t = useTranslation();
        const selectedItems = this.allItems.filter(item => this.selectedItems.includes(item.id));
        return (h(Host, { key: '60cb4988b91bbd62e4c79aa6492c74b4b9634aec' }, h("div", { key: '608408b1819f2049ebcc071b37ef2fed91ae8928', id: `auto-complete-${this.referenceSelector}`, class: "autocomplete-multiple-select" }, h("div", { key: 'a6482bbc0987af9b96d50f759b611ad6ff953aa1', class: "autocomplete-multiple-select-wrapper border-divider bg-background focus-within:border-primary", onClick: () => this.triggerEl.focus() }, h("div", { key: '1354f070aec74d366d6e6308ee9de28928e92739', class: "autocomplete-multiple-select-content" }, selectedItems.map(item => (h(ZTagOrStatusItem, { item: item, onDelete: () => this.removeChip(item.id) }))), h("input", { key: 'c6d1ad63df0acc0c49d79fae5730c0d4d0291395', class: "autocomplete-multiple-select-input bg-background text-surface", value: this.inputValue, onInput: this.onInput, onFocus: this.onFocus, ref: el => (this.triggerEl = el), id: this.referenceSelector })), h("div", { key: '6898ebcfe275f2e3662d001cf14029af9dadda23', class: "autocomplete-multiple-select-adornment" }, this.showClearButton && this.selectedItems.length > 0 && (h("slot", { key: '755833f69cea3259c58c0e841ac10ef4a7160d0f' }, h("div", { key: '72e537837953f7c2ec541eace3acbdc368e23700', class: "autocomplete-multiple-select-item-input-icon", onClick: () => this.onClearItem() }, h(Icon, { key: 'cdad2d32f6cdca02b6a8b97ee6dbb871f6b84804', name: "X" })), h("div", { key: '82f5c7d916dfe6afac1c02309674c24549414ffe', class: "bg-theme-gray h-5 w-px " }))), h("div", { key: '96a7b28c2c809b8726fce4c92b4a1b908d586809', class: "autocomplete-multiple-select-item-input-icon", onClick: this.toggleDropdown }, h(Icon, { key: '17556842b7e4bbde270f5fd4bd091b7585d23d27', name: "ChevronDown" })))), h("ul", { key: '2847dbc8f31a294fbabd7b8a9629b2c85d677e1d', ref: el => (this.popperEl = el), class: `autocomplete-multiple-select-list bg-background text-surface ${this.showDropdown ? '' : 'hidden!'}`, onScroll: this.handleScroll }, this.showSelectAllButton && this.filteredItems.length > 0 && (h("li", { key: '75f71e24ada94f5c319e02ae2beba9fd50859e5f', class: "autocomplete-multiple-select-item border-b border-divider font-semibold text-primary", onClick: this.onSelectAll }, h("div", { key: '95ef330e66b51f9828a15f2dcc7a0844f5c899d2', class: "truncate" }, t('select_all')))), this.filteredItems.length > 0
            ? this.filteredItems.map(item => {
                const isSelected = this.selectedItems.includes(item.id);
                return (h("li", { title: item.name, class: `autocomplete-multiple-select-item ${isSelected ? `bg-background` : 'hover:brightness-110'}`, onClick: () => !isSelected && this.onSelectItem(item) }, this.referenceSelector === 'filter-channel' &&
                    h(Fragment, null, item.iconName && h("img", { src: `https://zwizai-platform.s3.ap-southeast-1.amazonaws.com/zignal-package/${item.iconName}.png`, alt: "agent avatar", class: "size-4 rounded-full mr-2", loading: "lazy" }), item.subIconName && h("img", { src: `https://zwizai-platform.s3.ap-southeast-1.amazonaws.com/zignal-package/${item.subIconName}.png`, alt: "agent avatar", class: "size-4 rounded-full mr-2", loading: "lazy" })), item.color && h("span", { class: "autocomplete-multiple-select-icon", style: { backgroundColor: item.color } }), h("div", { class: "truncate" }, item.name), isSelected && h("span", { class: "autocomplete-multiple-select-text text-primary" }, "(", t('selected'), ")")));
            })
            : !this.loading ? (h("li", { class: "autocomplete-multiple-select-item border-b border-divider font-semibold text-primary cursor-not-allowed", onClick: () => this.showDropdown = false }, h("div", { class: "truncate" }, t('not_found')))) : null, this.loading && (h("li", { key: '921eadd33cdbb11a19b80094223e6ccd26238819', class: "autocomplete-multiple-select-item flex justify-center border-b border-divider font-semibold text-primary" }, h("status-badge", { key: 'da20e109248b0f20f1b2feb4ab10233745073168', status: "loading", label: t('loading') })))))));
    }
    static get is() { return "autocomplete-multiple-select"; }
    static get originalStyleUrls() {
        return {
            "$": ["autocomplete-multiple-select.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["autocomplete-multiple-select.css"]
        };
    }
    static get properties() {
        return {
            "fetchItems": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(params?: { search?: string; limit?: number; offset?: number }) => Promise<any>",
                    "resolved": "(params?: { search?: string; limit?: number; offset?: number; }) => Promise<any>",
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    }
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "selectedIds": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "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"
            },
            "showClearButton": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "show-clear-button",
                "defaultValue": "false"
            },
            "showSelectAllButton": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "show-select-all-button",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "allItems": {},
            "filteredItems": {},
            "inputValue": {},
            "showDropdown": {},
            "loading": {},
            "selectedItems": {},
            "totalItems": {}
        };
    }
    static get events() {
        return [{
                "method": "selecting",
                "name": "selecting",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "showDropdown",
                "methodName": "handleDropdownChange"
            }];
    }
}
