import { Schema, StringValue } from "@coveo/bueno";
import { buildSearchStatus, buildSort, buildTabManager, loadSortCriteriaActions, parseCriterionExpression } from "@coveo/headless";
import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import { guard } from "lit/directives/guard.js";
import { map } from "lit/directives/map.js";
import { renderSortLabel } from "../../common/sort/label.js";
import { renderSortOption } from "../../common/sort/option.js";
import { renderSortSelect } from "../../common/sort/select.js";
import { sortGuard } from "../../common/sort/sort-guard.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { shouldDisplayOnCurrentTab } from "../../../utils/tab-utils.js";
import { randomID } from "../../../utils/utils.js";
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
class AtomicSortDropdown extends LitElement {
    initialize() {
        this.buildOptions();
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.sort = buildSort(this.bindings.engine, {
            initialState: {
                criterion: this.bindings.store.state.sortOptions[0]?.criteria
            }
        });
        this.tabManager = buildTabManager(this.bindings.engine);
    }
    buildOptions() {
        const sortExpressionElements = Array.from(this.querySelectorAll('atomic-sort-expression'));
        if (!sortExpressionElements.length) {
            this.error = new Error('The "atomic-sort-dropdown" element requires at least one "atomic-sort-expression" child.');
            return;
        }
        this.bindings.store.state.sortOptions = sortExpressionElements.map((element)=>{
            const expression = element.getAttribute('expression') || '';
            const label = element.getAttribute('label') || '';
            const tabsIncluded = JSON.parse(element.getAttribute('tabs-included') || '[]');
            const tabsExcluded = JSON.parse(element.getAttribute('tabs-excluded') || '[]');
            new Schema({
                label: new StringValue({
                    emptyAllowed: false,
                    required: true
                })
            }).validate({
                label
            });
            return {
                tabs: {
                    included: tabsIncluded,
                    excluded: tabsExcluded
                },
                criteria: parseCriterionExpression(expression),
                expression,
                label
            };
        });
    }
    get options() {
        return this.bindings.store.state.sortOptions.filter(({ tabs })=>shouldDisplayOnCurrentTab([
                ...tabs.included
            ], [
                ...tabs.excluded
            ], this.tabManagerState?.activeTab));
    }
    select(e) {
        const select = e.composedPath()[0];
        const option = this.options.find((option)=>option.expression === select.value);
        option && this.sort.sortBy(option.criteria);
    }
    resetSortIfInvalidForCurrentTab() {
        if (!this.bindings || !this.sortState) return;
        if (this.isSortValid()) return;
        const criterion = this.options[0]?.criteria;
        if (!criterion) return;
        const action = loadSortCriteriaActions(this.bindings.engine).updateSortCriterion(this.options[0]?.criteria);
        this.bindings.engine.dispatch(action);
    }
    isSortValid() {
        return this.options.some((option)=>option.expression.trim().replace(/\s*,\s*/g, ',') === this.sortState.sortCriteria.replace(/@/g, ''));
    }
    renderSortLabelTemplate() {
        return renderSortLabel({
            props: {
                id: this.dropdownId,
                i18n: this.bindings.i18n
            }
        });
    }
    renderSortSelectTemplate() {
        const { bindings: { i18n }, dropdownId: id } = this;
        return renderSortSelect({
            props: {
                i18n,
                id,
                onSelect: (evt)=>this.select(evt)
            }
        })(html`${guard([
            this.sortState,
            this.options
        ], ()=>map(this.options, ({ label, criteria, expression })=>renderSortOption({
                    props: {
                        i18n,
                        label,
                        selected: this.sort.isSortedBy(criteria),
                        value: expression
                    }
                })))}`);
    }
    render() {
        const { hasError, hasResults, firstSearchExecuted, isLoading } = this.searchStatusState;
        return html`
      ${sortGuard({
            isLoading,
            firstSearchExecuted,
            hasResults,
            hasError
        }, ()=>html`<div class="text-on-background flex flex-wrap items-center">
            ${this.renderSortLabelTemplate()} ${this.renderSortSelectTemplate()}
          </div>`)}
      <slot></slot>
    `;
    }
    constructor(...args){
        super(...args), this.dropdownId = randomID('atomic-sort-dropdown-'), this.onTabManagerStateChange = ()=>{
            this.resetSortIfInvalidForCurrentTab();
        };
    }
}
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicSortDropdown.prototype, "bindings", void 0);
_ts_decorate([
    bindStateToController('sort'),
    state(),
    _ts_metadata("design:type", "u" < typeof SortState ? Object : SortState)
], AtomicSortDropdown.prototype, "sortState", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    state(),
    _ts_metadata("design:type", "u" < typeof SearchStatusState ? Object : SearchStatusState)
], AtomicSortDropdown.prototype, "searchStatusState", void 0);
_ts_decorate([
    bindStateToController('tabManager', {
        onUpdateCallbackMethod: 'onTabManagerStateChange'
    }),
    state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicSortDropdown.prototype, "tabManagerState", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicSortDropdown.prototype, "error", void 0);
_ts_decorate([
    errorGuard(),
    bindingGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSortDropdown.prototype, "render", null);
AtomicSortDropdown = _ts_decorate([
    customElement('atomic-sort-dropdown'),
    bindings(),
    withTailwindStyles
], AtomicSortDropdown);
export { AtomicSortDropdown };
