import { Host, h, Fragment } from "@stencil/core";
import { loadThaiAddresses } from "../../utils/address-loader";
import { computePosition, autoUpdate, offset, flip, shift } from "@floating-ui/dom";
import { useTranslation } from "../../utils/utils";
import { userAddressStore } from "../../store/store";
import { ZIconButton } from "../internal-component/z-icon-button";
export class AutocompleteAddress {
    field;
    value;
    selectedValue;
    placeholder;
    referenceSelector;
    selecting;
    allItems = [];
    showDropdown = false;
    isLoading = false;
    triggerEl;
    popperEl;
    addressData = [];
    disposeListener;
    cleanup;
    async initialAddresses(currentAddress) {
        // Lazy load address data if not already loaded
        if (this.addressData.length === 0) {
            try {
                this.isLoading = true;
                this.addressData = await loadThaiAddresses();
            }
            catch (error) {
                console.error('Failed to load Thai addresses:', error);
                this.isLoading = false;
                return;
            }
            finally {
                this.isLoading = false;
            }
        }
        const seen = new Set();
        const filteredAddress = [];
        for (const item of this.addressData.filter(item => {
            if (currentAddress) {
                switch (this.field) {
                    case 'a':
                        return item.p === currentAddress.province;
                    case 'd':
                        return item.a === currentAddress.district;
                    case 'z':
                        return item.d === currentAddress.sub_district;
                    default:
                        return true;
                }
            }
            else {
                return true;
            }
        })) {
            const value = item[this.field];
            if (value != null) {
                const str = String(value);
                if (!seen.has(str)) {
                    seen.add(str);
                    filteredAddress.push(str);
                }
            }
        }
        this.allItems = filteredAddress;
    }
    async componentWillLoad() {
        await this.initialAddresses(userAddressStore.get('userAddress'));
        this.disposeListener = userAddressStore.onChange('userAddress', async (newAddress) => {
            if (!newAddress) {
                return;
            }
            await this.initialAddresses(newAddress);
        });
    }
    componentDidLoad() {
        document.addEventListener('click', this.handleClickOutside);
        window.addEventListener('close-all-poppers', this.handleCloseOthers);
        this.handleClose();
    }
    disconnectedCallback() {
        document.removeEventListener('click', this.handleClickOutside);
        window.removeEventListener('close-all-poppers', this.handleCloseOthers);
        this.handleClose();
        if (this.disposeListener)
            this.disposeListener();
    }
    handleClickOutside = (e) => {
        const path = e.composedPath();
        if (!path.includes(this.triggerEl) && !path.includes(this.popperEl)) {
            this.handleClose();
        }
    };
    handleCloseOthers = (e) => {
        if (e.detail !== this && this.showDropdown) {
            this.handleClose();
        }
    };
    handleClose = () => {
        this.showDropdown = false;
        if (this.cleanup)
            this.cleanup();
        if (this.popperEl)
            this.popperEl.remove();
    };
    onInput = (e) => {
        const value = e.target.value;
        this.selecting.emit(value);
        this.showDropdown = true;
    };
    onSelectItem = (item) => {
        this.selecting.emit(item);
        this.handleClose();
    };
    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();
        }
    };
    render() {
        const t = useTranslation();
        const filteredItems = this.allItems.filter(item => {
            if (this.value && this.value.length > 0) {
                return (item ? item.toLowerCase() : '').includes(this.value.toLowerCase());
            }
            else {
                return true;
            }
        });
        return (h(Host, null, h("div", { id: `auto-complete-address-${this.referenceSelector}`, class: "autocomplete-address" }, h("div", { class: "autocomplete-address-wrapper" }, h("input", { class: "autocomplete-address-input", value: this.value, onInput: this.onInput, onFocus: () => this.onFocus(), ref: el => (this.triggerEl = el), id: this.referenceSelector, placeholder: t(this.placeholder) }), h("div", { class: "autocomplete-address-input-action", onClick: () => {
                if (this.value && this.value.length > 0) {
                    this.selecting.emit('');
                }
                else {
                    setTimeout(() => {
                        this.onFocus();
                    }, 100);
                }
            } }, this.value && this.value.length > 0 ? (h(ZIconButton, { iconName: 'X', addClassIcon: "autocomplete-address-input-clear", variant: "none" })) : (h(ZIconButton, { iconName: 'Triangle', addClassIcon: "autocomplete-address-input-arrow-down", variant: "none" })))), h("ul", { ref: el => (this.popperEl = el), class: "autocomplete-address-list" }, this.isLoading ? (h("li", { class: "autocomplete-address-list-loading-wrapper" }, h("div", { class: "autocomplete-address-item" }, "Loading..."))) : (h(Fragment, null, filteredItems.map(item => {
            const value = this.value || '';
            const isSelected = (item ? item.toLowerCase() : '') === value.toLowerCase();
            return (h("li", { title: item, class: `autocomplete-address-item-wrapper ${isSelected ? '' : 'hover:brightness-110'} cursor-pointer ${isSelected ? 'bg-background' : ''}`, onClick: () => this.onSelectItem(item) }, h("div", { class: "autocomplete-address-item" }, item)));
        }), filteredItems.length === 0 && (h("li", { class: "autocomplete-address-item-wrapper bg-background" }, h("div", { class: "autocomplete-address-item" }, t('not_found'), "\u00A0", t(this.placeholder))))))))));
    }
    static get is() { return "autocomplete-address"; }
    static get originalStyleUrls() {
        return {
            "$": ["autocomplete-address.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["autocomplete-address.css"]
        };
    }
    static get properties() {
        return {
            "field": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "keyof IThaiAddress",
                    "resolved": "\"a\" | \"aE\" | \"d\" | \"dE\" | \"p\" | \"pE\" | \"z\"",
                    "references": {
                        "IThaiAddress": {
                            "location": "import",
                            "path": "../../constants/address",
                            "id": "src/constants/address.ts::IThaiAddress",
                            "referenceLocation": "IThaiAddress"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "field"
            },
            "value": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value"
            },
            "selectedValue": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "selected-value"
            },
            "placeholder": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "placeholder"
            },
            "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 {
            "allItems": {},
            "showDropdown": {},
            "isLoading": {}
        };
    }
    static get events() {
        return [{
                "method": "selecting",
                "name": "selecting",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                }
            }];
    }
}
