import { Host, h } from "@stencil/core";
import { computePosition, autoUpdate, offset, flip, shift } from "@floating-ui/dom";
import { useTranslation } from "../../utils/utils";
import { GET_USER_TAG_PAGE_LIMIT, TAG_LENGTH } from "../../utils/constant";
import { Icon } from "../internal-component/icon";
export class AutocompleteSelect {
    type = 'status';
    value;
    fetchItems;
    createItem;
    selectedIds;
    referenceSelector;
    showClearButton = false;
    placeholder;
    hideLabelUsed = false;
    showNoOption = false;
    selecting;
    create;
    clear;
    allItems = [];
    filteredItems = [];
    inputValue = '';
    showDropdown = false;
    loading = true;
    triggerEl;
    popperEl;
    cleanup;
    totalItems = -1;
    offset = 0;
    limit = GET_USER_TAG_PAGE_LIMIT;
    isBackendPaginated = false;
    searchTimeout;
    searchValue = '';
    async componentWillLoad() {
        if (typeof this.value === 'string') {
            this.inputValue = this.value;
        }
        await this.loadItems(true);
    }
    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.searchValue) {
                fetchParams.search = this.searchValue;
            }
            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;
                }
            }
            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.searchValue.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.searchValue = 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.type === 'status') {
            this.inputValue = item.name;
            this.searchValue = '';
        }
        else {
            this.inputValue = '';
            this.searchValue = '';
        }
        this.showDropdown = false;
        this.selecting.emit(item);
    };
    async onCreateItem() {
        const value = this.inputValue.trim();
        if (value === '')
            return;
        const existItem = this.allItems.find(i => i.name.toLowerCase() === value.toLowerCase());
        if (existItem) {
            this.onSelectItem(existItem);
            return;
        }
        const newItem = await this.createItem(value);
        await this.loadItems(true);
        this.create.emit(newItem);
        this.onSelectItem(newItem);
        if (this.type === 'tag') {
            this.inputValue = '';
        }
    }
    onClearItem() {
        this.clear.emit();
        this.searchValue = '';
        this.onSelectItem({ id: '', name: '' });
    }
    toggleDropdown = (e) => {
        e.stopPropagation();
        if (this.showDropdown) {
            this.showDropdown = false;
        }
        else {
            this.triggerEl?.focus();
            this.onFocus();
        }
    };
    onFocus = () => {
        this.showDropdown = true;
        if (this.showDropdown) {
            window.dispatchEvent(new CustomEvent('close-all-poppers', { detail: this }));
            const referenceEl = this.triggerEl;
            if (!referenceEl || !this.popperEl)
                return;
            const container = document.getElementById('chat-app') || document.body;
            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, {
                        left: `${x}px`,
                        top: `${y}px`,
                        zIndex: '9999',
                    });
                });
            });
        }
        else {
            if (this.cleanup)
                this.cleanup();
            if (this.popperEl)
                this.popperEl.remove();
        }
    };
    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 selectedValue = this.allItems.find(i => i.id === this.inputValue)?.name || this.inputValue;
        const noMatch = selectedValue && !this.allItems.some(i => i.name.toLowerCase() === selectedValue.toLowerCase());
        return (h(Host, { key: 'f978238b92e785a8485cf9181ea77d5a82b86871' }, h("div", { key: 'b4c752c3e2ad9ae32758477289cce96ad4bc0427', id: `auto-complete-${this.referenceSelector}`, class: "autocomplete-select" }, h("div", { key: 'da9ea5ffee676baf816b4aaf9cec3296ab5cfc72', class: "autocomplete-select-wrapper border-divider bg-background focus-within:border-primary", onClick: () => this.triggerEl?.focus() }, h("div", { key: '734811148234d278c0d3d9a71136e6704aef6b7c', class: "autocomplete-select-content" }, h("input", { key: 'ce8a21f935439ac93a88a484041e823aa0390173', class: "autocomplete-select-input bg-background text-surface", value: selectedValue, placeholder: this.placeholder, onInput: this.onInput, onFocus: this.onFocus, maxLength: this.type === 'tag' ? TAG_LENGTH : undefined, onKeyDown: e => e.key === 'Enter' && this.showDropdown && this.onCreateItem(), ref: el => (this.triggerEl = el), id: this.referenceSelector }), this.type === 'tag' &&
            h("div", { key: '98a6f82c9c408ed365091e9325701fc87b457f89', class: "autocomplete-select-item-counter" }, "(", selectedValue.length, "/", TAG_LENGTH, ")")), h("div", { key: '01d715e8a9f0794f401017280bbbd9a04760ca31', class: "autocomplete-select-adornment" }, this.showClearButton && selectedValue &&
            h("slot", { key: '8c256ce474dc8952f056ebf9d0274fe89539a5a8' }, h("div", { key: 'b3e66eda0e845f497bffea9f337bdc5646268cc9', class: "autocomplete-select-item-input-icon", onClick: () => this.onClearItem() }, h(Icon, { key: '671d7befbe73aa8ce36821e9a8322f1f3efa61cb', name: "X" })), h("div", { key: '225f635061ee7f054f668cbb6946184f70494b08', class: "bg-theme-gray h-5 w-px " })), h("div", { key: '38c25fb0385a23cb8a61cc3ee1134ef77fedf0fa', class: "autocomplete-select-item-input-icon", onClick: this.toggleDropdown }, h(Icon, { key: '1ea9d0740c7e7650b08017fdc499bb366491e385', name: "ChevronDown" })))), h("ul", { key: '2015d495ad218f7308932d96f42ef8386e5919b4', ref: el => (this.popperEl = el), class: `autocomplete-select-list ${(this.showDropdown && (this.filteredItems.length > 0 || selectedValue || this.showNoOption || this.loading)) ? '' : 'hidden!'}`, onScroll: this.handleScroll }, noMatch && this.createItem && (h("li", { key: '5cb7f9177729ebcc7fdd69190b55727d813908f8', title: selectedValue, class: "autocomplete-select-item-wrapper", onClick: () => this.onCreateItem() }, h("span", { key: '645da20d17e0e91d7a8b03176abf0f32444019c0', class: "autocomplete-select-text-primary" }, t('new'), "\u00A0:\u00A0"), "\u00A0", h("strong", { key: '36b2ecc6faa4314c9d3c7aad5588fcdc3be65691' }, selectedValue), "\u00A0", h("span", { key: '888aec8b98d42c6f472d0c320249d7c07df900e9', class: "font-semibold text-theme-gray" }, t('enter_create')))), this.filteredItems.length > 0
            ? this.filteredItems.map(item => {
                const isSelected = this.type === 'tag'
                    ? (this.selectedIds || []).includes(item ? item.id : '')
                    : (item ? item.name : '').toLowerCase() === (selectedValue || '').toLowerCase();
                return (h("li", { title: item.name, class: `autocomplete-select-item ${isSelected ? '' : 'hover:brightness-110'} cursor-pointer ${isSelected ? `bg-background` : ''} ${item.disabled ? 'opacity-50 cursor-not-allowed' : ''}`, onClick: () => !item.disabled && this.onSelectItem(item) }, item.color && (() => {
                    const isCssColor = item.color.startsWith('#') || item.color.startsWith('rgb');
                    return isCssColor
                        ? h("span", { class: "autocomplete-select-item-icon", style: { backgroundColor: item.color } })
                        : h("span", { class: `autocomplete-select-item-icon ${item.color}` });
                })(), h("div", { class: "autocomplete-select-item-text" }, item.name), !this.hideLabelUsed && isSelected && h("span", { class: "autocomplete-select-text-primary" }, "\u00A0(", t('used'), ")")));
            })
            : (!this.loading && this.showNoOption ? h("li", { class: "autocomplete-select-item", onClick: () => this.showDropdown = false }, t('no_options')) : null), this.loading && (h("li", { key: '2cd3634bd5993e575c4d837f48056ef58414d342', class: "autocomplete-select-item flex justify-center border-b border-divider font-semibold text-primary" }, h("status-badge", { key: '816501b28284b01398f52b9c8178c3600b264627', status: "loading", label: t('loading') })))))));
    }
    static get is() { return "autocomplete-select"; }
    static get originalStyleUrls() {
        return {
            "$": ["autocomplete-select.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["autocomplete-select.css"]
        };
    }
    static get properties() {
        return {
            "type": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'tag' | 'status'",
                    "resolved": "\"status\" | \"tag\"",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "type",
                "defaultValue": "'status'"
            },
            "value": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | string[]",
                    "resolved": "string | string[]",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value"
            },
            "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
            },
            "createItem": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(name: string) => Promise<ItemType>",
                    "resolved": "(name: string) => Promise<ItemType>",
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "ItemType": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::ItemType",
                            "referenceLocation": "ItemType"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "selectedIds": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "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"
            },
            "placeholder": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "placeholder"
            },
            "hideLabelUsed": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "hide-label-used",
                "defaultValue": "false"
            },
            "showNoOption": {
                "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-no-option",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "allItems": {},
            "filteredItems": {},
            "inputValue": {},
            "showDropdown": {},
            "loading": {},
            "totalItems": {}
        };
    }
    static get events() {
        return [{
                "method": "selecting",
                "name": "selecting",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ItemType",
                    "resolved": "TTagOrStatusItem & { disabled?: boolean; }",
                    "references": {
                        "ItemType": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::ItemType",
                            "referenceLocation": "ItemType"
                        }
                    }
                }
            }, {
                "method": "create",
                "name": "create",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ItemType",
                    "resolved": "TTagOrStatusItem & { disabled?: boolean; }",
                    "references": {
                        "ItemType": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::ItemType",
                            "referenceLocation": "ItemType"
                        }
                    }
                }
            }, {
                "method": "clear",
                "name": "clear",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
}
