import { h, Host } from "@stencil/core";
import { cls, getId, isEmpty } from "../../utils/helpers";
import { autoUpdate, computePosition, flip, offset, shift, size } from "@floating-ui/dom";
import { Lang } from "../../services/lang";
export class XSelect {
    constructor() {
        /**
         * Element ID for internal reference
         */
        this.inputId = getId('select');
        this.label = undefined;
        this.name = undefined;
        this.placeholder = undefined;
        this.info = undefined;
        this.required = undefined;
        this.loading = undefined;
        this.autofocus = undefined;
        this.multiple = undefined;
        this.size = undefined;
        this.autocomplete = 'off';
        this.value = '';
        this.isValid = true;
        this.isFocused = undefined;
        this.isLoading = undefined;
        this.isDisabled = undefined;
        this.isFiltered = undefined;
        this.computedValue = [];
        this.computedText = [];
        this.filteredCount = undefined;
        this.filteredTotal = undefined;
    }
    /**
     * Watch changes in value property
     */
    watchValue(newValue) {
        var _a;
        this.selectOptionByValue(newValue);
        this.el.dispatchEvent(new InputEvent('input', { bubbles: true }));
        this.formValidateCallback(this.isReady);
        (_a = this.internals.form) === null || _a === void 0 ? void 0 : _a.dispatchEvent(new InputEvent('input', { bubbles: false }));
        if (!this.isReady) {
            this.isReady = true;
        }
    }
    /**
     * on child option element is triggered the selection
     */
    handleOptionSelected(ev) {
        if (this.multiple) {
            this.computedValue.includes(ev.detail.value) ?
                this.computedValue.splice(this.computedValue.indexOf(ev.detail.value), 1) :
                this.computedValue.push(ev.detail.value);
            this.computedText.includes(ev.detail.text) ?
                this.computedText.splice(this.computedText.indexOf(ev.detail.text), 1) :
                this.computedText.push(ev.detail.text);
        }
        else {
            this.computedValue = this.computedValue.includes(ev.detail.value) ? [] : [ev.detail.value];
            this.computedText = this.computedText.includes(ev.detail.text) ? [] : [ev.detail.text];
        }
        Array.from(this.el.querySelectorAll('x-select-option'))
            .filter(el => this.computedValue.includes(el.value) || el.selected)
            .forEach((el) => {
            el.selected = this.computedValue.includes(el.value);
        });
        const input = this.el.querySelector('.select-input');
        input.value = '';
        input.dispatchEvent(new InputEvent('input', { bubbles: false }));
        this.setFormValue();
    }
    /**
     * Element event on slot make changes
     */
    handleSlotChange() {
        this.selectOptionByValue(this.value);
    }
    /**
     * Set the actual value to internals
     */
    setFormValue() {
        var _a;
        if (this.multiple) {
            this.value = this.computedValue;
            if (!((_a = this.name) === null || _a === void 0 ? void 0 : _a.length)) {
                return;
            }
            const data = new FormData();
            this.computedValue.forEach((value) => {
                data.append(this.name, value);
            });
            this.internals.setFormValue(data);
        }
        else {
            this.value = this.computedValue[0];
            this.internals.setFormValue(this.computedValue[0]);
        }
    }
    /**
     * This is called on component will load
     */
    componentWillLoad() {
        if (this.isAdvancedSelect()) {
            this.value = Array.from(this.el.querySelectorAll('x-select-option'))
                .filter(el => el.selected)
                .reduce((_, el) => {
                return Array.isArray(_) ? _.push(el.value) && _ : el.value;
            }, this.multiple ? [] : '');
        }
    }
    /**
     * This is called on component did load
     */
    componentDidLoad() {
        setTimeout(() => {
            this.formValidateCallback();
            this.selectOptionByValue(this.value);
        }, 0);
    }
    /**
     * This is called on component did update the element space
     */
    computePositionCustomSelect() {
        if (this.isAdvancedSelect()) {
            const container = this.el.querySelector('.select-items');
            computePosition(this.el, container, {
                placement: 'bottom-start',
                middleware: [size({
                        apply({ availableWidth, availableHeight, elements }) {
                            const items = elements;
                            if (document.documentElement.clientWidth <= 480) {
                                container.style.maxWidth = null;
                            }
                            else {
                                container.style.maxWidth = `${Math.max(200, availableWidth > items.reference.offsetWidth ? items.reference.offsetWidth : availableWidth)}px`;
                            }
                            container.style.maxHeight = `${Math.max(200, availableHeight - 4)}px`;
                        }
                    }), flip(), shift(), offset(4)],
            }).then(({ x, y }) => {
                container.style.left = `${x}px`;
                container.style.top = `${y}px`;
            });
        }
    }
    /**
     * This is called when the 'disabled' attribute of the element or or an ancestor <fieldset> is updated
     *
     * @param disabled
     */
    formDisabledCallback(disabled) {
        this.isDisabled = disabled;
    }
    /**
     * This is called when the parent/owner form is reset
     */
    formResetCallback() {
        this.isValid = true;
        this.internals.setFormValue('');
        const placeholder = this.el.querySelector('[data-placeholder]');
        placeholder && placeholder.setAttribute('selected', 'selected');
    }
    /**
     * This is called when the input is validated
     */
    formValidateCallback(dispatchValidation) {
        var _a, _b;
        if (this.required && isEmpty(this.value)) {
            this.internals.setValidity({ valueMissing: true }, Lang.get('fields.validation.value-missing'));
        }
        else {
            this.internals.setValidity({});
        }
        if (dispatchValidation) {
            this.isValid = this.isAdvancedSelect() ? this.internals.validity.valid : (_b = (_a = this.input) === null || _a === void 0 ? void 0 : _a.validity) === null || _b === void 0 ? void 0 : _b.valid;
            this.onValidateInputEvent.emit(this.isAdvancedSelect() ? this.internals : this.input);
        }
    }
    /**
     * Set element value by event
     *
     * @param event
     */
    onInput(event) {
        this.value = event.target.value;
        this.internals && this.internals.setFormValue(event.target.value);
    }
    /**
     * This called on input field is unfocused
     */
    onBlurInput() {
        setTimeout(() => {
            this.isFocused = false;
            this.formValidateCallback(true);
            this.cleanup && this.cleanup();
        }, 20);
    }
    /**
     * This called on input field is focused
     */
    onFocusInput() {
        this.isFocused = true;
        if (this.isAdvancedSelect()) {
            this.cleanup = autoUpdate(this.el, this.el.querySelector('.select-items'), this.computePositionCustomSelect.bind(this));
        }
    }
    /**
     * This called on search input have results
     */
    onFilterInput(ev) {
        this.isFiltered = ev.target.value.length > 0;
        setTimeout(() => {
            this.filteredTotal = this.el.querySelectorAll('x-select-option').length;
            this.filteredCount = this.el.querySelectorAll('x-select-option[matched]').length;
        }, 50);
    }
    /**
     * Return validation of showing the input label
     *
     * @returns
     */
    showLabel() {
        var _a, _b;
        return (this.label && this.placeholder) || (this.label && (((_b = (_a = this.value) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '').length > 0 || this.computedValue.length > 0 || this.isFocused || (this.multiple && !this.isAdvancedSelect())));
    }
    /**
     * Compute the placeholder value
     *
     * @returns
     */
    placeholderValue() {
        if (this.label) {
            if (this.placeholder) {
                return this.placeholder;
            }
            else if (!this.showLabel() || (this.multiple && this.isAdvancedSelect())) {
                return this.label;
            }
        }
        return this.placeholder;
    }
    /**
     * Focus the select input
     */
    focusSelect() {
        var _a;
        const event = new MouseEvent("mousedown", {
            bubbles: true,
            cancelable: true,
            view: window,
        });
        if (this.isAdvancedSelect()) {
            this.isFocused = !this.isFocused;
            setTimeout(() => {
                this.el.querySelector('.select-input').focus();
            }, 20);
        }
        else {
            (_a = this.input) === null || _a === void 0 ? void 0 : _a.dispatchEvent(event);
        }
    }
    /**
     * Select the option element by value
     */
    selectOptionByValue(value) {
        const options = Array.from(this.el.children)
            .filter(el => el.nodeName.toLowerCase() === 'option')
            .map(el => el);
        options && options.length > 0 && options.forEach((option) => {
            if (Array.isArray(value) ? value.includes(option.value) : option.value === value.toString()) {
                option.selected = true;
            }
        });
        if (this.isAdvancedSelect) {
            const xoptions = Array.from(this.el.querySelectorAll('x-select-option'));
            this.computedValue = [];
            this.computedText = [];
            xoptions && xoptions.forEach(async (el) => {
                var _a;
                if (Array.isArray(value) ? value.includes(el.value) : value == el.value) {
                    el.selected = true;
                }
                if (el.selected) {
                    this.computedValue.push(el.value);
                    this.computedText.push((_a = el.ariaLabel) !== null && _a !== void 0 ? _a : await el.updateText());
                }
            });
        }
    }
    /**
     * Check if the select use not native options
     */
    isAdvancedSelect() {
        return this.el.querySelector("x-select-option") !== null;
    }
    /**
     * Render component
     */
    render() {
        return h(Host, { key: '102e211d6ed889ada65f6807302777e290737abd', "data-for": this.name }, h("div", { key: '37c73d5ea2040b9e83e84fd73bf5a5ed555fbbf7', class: cls("input-container", {
                "focus": this.isFocused,
                "loading": this.loading || this.isLoading,
                "disabled": this.isDisabled,
                "invalid": !this.isValid,
                "required": this.required,
                "multiple": this.multiple,
                "advanced": this.isAdvancedSelect(),
            }) }, h("div", { key: '70352a11eba958b5360016f624cfcee68c83968f', class: "indicator" }, h("slot", { key: 'b000c40bec80a74a5f514453c469937f7463021c', name: "indicator" })), h("div", { key: '943e7c5fe2fc16813edc951ea074227bdbc41911', class: "separator" }), h("div", { key: 'b9a74d6ec6698545efc5dc8d5e2f9344aec7e592', class: "wrap" }, this.showLabel() && h("label", { key: '9fd78bbae71051f3d83915a7ba8fb3af23acf022', htmlFor: this.inputId }, this.label), this.isAdvancedSelect() ?
            h("div", null, h("input", { id: this.inputId, onFocus: () => this.focusSelect(), style: { width: '0.1px', flex: 'none' }, value: this.computedText.join(', '), required: this.required, disabled: this.isDisabled || this.loading || this.isLoading }), (!this.isFocused || this.multiple) &&
                h("p", { style: { width: this.isFocused ? 'max-content' : '100%' }, onClick: () => this.focusSelect() }, this.computedText.join(', ')), h("input", { tabindex: "-1", id: this.inputId, style: { display: this.isFocused || this.computedValue.length < 1 ? 'block' : 'none' }, class: "select-input", type: "text", autoFocus: this.autofocus, placeholder: this.placeholderValue(), onInput: (ev) => this.onFilterInput(ev), onBlur: () => this.onBlurInput(), onFocus: () => this.onFocusInput() }))
            : h("select", { ref: el => this.input = el, id: this.inputId, required: this.required, disabled: this.isDisabled || this.loading || this.isLoading, autoComplete: this.autocomplete, autoFocus: this.autofocus, multiple: this.multiple, size: this.size, onInput: (e) => this.onInput(e), onBlur: () => this.onBlurInput(), onFocus: () => this.onFocusInput() }, this.placeholder && h("option", { value: "", selected: true, disabled: true, "data-placeholder": true }, this.placeholder), h("slot", null))), h("div", { key: 'aa82d7c1965f24eca469cdf800017f018579b49c', class: "field-float-components" }, this.loading && h("div", { key: 'c133208599e89fc9705212f68a760065844b0456', class: "loading-indicator" }), h("div", { key: 'acc230828e8e52ed0baa30d3cc190555ae58f15e', class: "buttons" }, !(this.multiple && !this.isAdvancedSelect()) && h("x-button", { key: 'c22a5e8faf665cf27c44fb0b60e2b7a4e4dad50a', tabindex: "-1", class: "dropdown-button", icon: "dropdown", onClick: () => this.focusSelect() }), h("slot", { key: '0705b96fb7ccaf37b062ab299422be2eb04b8dac', name: "buttons" })), this.info && h("div", { key: '9d5effa0223a27b28783b3c3a54241155bed2abd', class: "info" }, h("x-tooltip", { key: '71bada64fc3d0173694947e444ebf0b72203ff5d', content: this.info }, h("x-icon", { key: '494e22a63eb60d7a947954503eb28612edd8df8e', name: "info" }))))), this.isAdvancedSelect() && h("div", { key: '09784f89677b92ca5ec032fd55190d2f0dc5a479', class: cls('select-items', {
                'focused': this.isFocused,
                'filtered': this.isFiltered,
            }) }, h("slot", { key: 'd072802001fa37dbc57b0262c162ba29211cf363' }), this.isFiltered && h("div", { key: 'dc4bea4954df0f8b83e206bd850704b398213fa1', class: "select-results" }, h("span", { key: '2156cc5671f27d3895fc3affab44d1651836aec2' }, "Mostrando ", h("strong", { key: '367cc194e469a071e1416d7cffdf86c57d1959ae' }, this.filteredCount), " recomendacion(es) de ", h("strong", { key: '91db478fa44e4f5d40597bc7cb726c1ffd800e31' }, this.filteredTotal)))));
    }
    static get is() { return "x-select"; }
    static get formAssociated() { return true; }
    static get originalStyleUrls() {
        return {
            "$": ["./style.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["style.css"]
        };
    }
    static get properties() {
        return {
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input label text"
                },
                "attribute": "label",
                "reflect": false
            },
            "name": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input name for forms keys"
                },
                "attribute": "name",
                "reflect": false
            },
            "placeholder": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input placeholder text"
                },
                "attribute": "placeholder",
                "reflect": false
            },
            "info": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input information block"
                },
                "attribute": "info",
                "reflect": false
            },
            "required": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element input required for forms validations"
                },
                "attribute": "required",
                "reflect": false
            },
            "loading": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element show loading and block for edit"
                },
                "attribute": "loading",
                "reflect": false
            },
            "autofocus": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element autofocus on render"
                },
                "attribute": "autofocus",
                "reflect": false
            },
            "multiple": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element multiple selection"
                },
                "attribute": "multiple",
                "reflect": false
            },
            "size": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element rows size on multiple selection"
                },
                "attribute": "size",
                "reflect": false
            },
            "autocomplete": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "InputAutocompleteTypes",
                    "resolved": "\"name\" | \"on\" | \"off\" | \"tel\" | \"url\" | \"email\" | \"honorific-prefix\" | \"given-name\" | \"additional-name\" | \"family-name\" | \"honorific-suffix\" | \"nickname\" | \"username\" | \"new-password\" | \"current-password\" | \"one-time-code\" | \"organization-title\" | \"organization\" | \"street-address\" | \"address-line1\" | \"address-line2\" | \"address-line3\" | \"address-level4\" | \"address-level3\" | \"address-level2\" | \"address-level1\" | \"country\" | \"country-name\" | \"postal-code\" | \"cc-name\" | \"cc-given-name\" | \"cc-additional-name\" | \"cc-family-name\" | \"cc-number\" | \"cc-exp\" | \"cc-exp-month\" | \"cc-exp-year\" | \"cc-csc\" | \"cc-type\" | \"transaction-currency\" | \"transaction-amount\" | \"language\" | \"bday\" | \"bday-day\" | \"bday-month\" | \"bday-year\" | \"sex\" | \"tel-country-code\" | \"tel-national\" | \"tel-area-code\" | \"tel-local\" | \"tel-extension\" | \"impp\" | \"photo\"",
                    "references": {
                        "InputAutocompleteTypes": {
                            "location": "import",
                            "path": "../x-input/component",
                            "id": "src/components/x-input/component.tsx::InputAutocompleteTypes"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element input value of the control can be automatically completed by the browser"
                },
                "attribute": "autocomplete",
                "reflect": false,
                "defaultValue": "'off'"
            },
            "value": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string | Array<string> | null",
                    "resolved": "string | string[]",
                    "references": {
                        "Array": {
                            "location": "global",
                            "id": "global::Array"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input value"
                },
                "attribute": "value",
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "isValid": {},
            "isFocused": {},
            "isLoading": {},
            "isDisabled": {},
            "isFiltered": {},
            "computedValue": {},
            "computedText": {},
            "filteredCount": {},
            "filteredTotal": {}
        };
    }
    static get events() {
        return [{
                "method": "onValidateInputEvent",
                "name": "validated",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "On validate input event"
                },
                "complexType": {
                    "original": "ElementInternals|HTMLSelectElement",
                    "resolved": "ElementInternals | HTMLSelectElement",
                    "references": {
                        "ElementInternals": {
                            "location": "global",
                            "id": "global::ElementInternals"
                        },
                        "HTMLSelectElement": {
                            "location": "global",
                            "id": "global::HTMLSelectElement"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "value",
                "methodName": "watchValue"
            }];
    }
    static get listeners() {
        return [{
                "name": "option-selected",
                "method": "handleOptionSelected",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "slotchange",
                "method": "handleSlotChange",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
    static get attachInternalsMemberName() { return "internals"; }
}
