import { NumberValue, Schema, StringValue } from "@coveo/bueno";
import { buildDateFacet, buildDateFilter, buildDateRange, buildFacetConditionsManager, buildSearchStatus, deserializeRelativeDate, loadDateFacetSetActions } from "@coveo/headless/insight";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { parseDependsOn } from "../../common/facets/depends-on.js";
import facet_common_tw_css from "../../common/facets/facet-common.tw.css.js";
import { renderFacetPlaceholder } from "../../common/facets/facet-placeholder/facet-placeholder.js";
import { TimeframeFacetCommon } from "../../common/facets/timeframe-facet-common.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.js";
import { booleanConverter } from "../../../converters/boolean-converter.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 { FocusTargetController } from "../../../utils/accessibility-utils.js";
import { mapProperty } from "../../../utils/props-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 AtomicInsightTimeframeFacet extends LitElement {
    get focusTarget() {
        if (!this.headerFocus) this.headerFocus = new FocusTargetController(this, this.bindings);
        return this.headerFocus;
    }
    initialize() {
        this.timeframeFacetCommon = new TimeframeFacetCommon({
            facetId: this.facetId,
            host: this,
            bindings: this.bindings,
            label: this.label,
            field: this.field,
            headingLevel: this.headingLevel,
            dependsOn: parseDependsOn(this.dependsOn) ? this.dependsOn : {},
            withDatePicker: this.withDatePicker,
            setFacetId: (id)=>{
                this.facetId = id;
                return id;
            },
            getSearchStatusState: ()=>this.searchStatusState,
            buildDependenciesManager: (facetId)=>buildFacetConditionsManager(this.bindings.engine, {
                    facetId,
                    conditions: parseDependsOn(this.dependsOn)
                }),
            deserializeRelativeDate: deserializeRelativeDate,
            buildDateRange: buildDateRange,
            initializeFacetForDatePicker: ()=>this.initializeFacetForDatePicker(),
            initializeFacetForDateRange: (values)=>this.initializeFacetForDateRange(values),
            initializeFilter: ()=>this.initializeFilter(),
            sortCriteria: this.sortCriteria
        });
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.addEventListener('atomic-date-input-apply', this.handleDateInputApply);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.timeframeFacetCommon?.disconnectedCallback();
        this.removeEventListener('atomic-date-input-apply', this.handleDateInputApply);
    }
    initializeFacetForDatePicker() {
        return buildDateFacet(this.bindings.engine, {
            options: {
                facetId: `${this.facetId}_input_range`,
                numberOfValues: 1,
                generateAutomaticRanges: true,
                field: this.field,
                filterFacetCount: this.filterFacetCount,
                injectionDepth: this.injectionDepth
            }
        });
    }
    initializeFacetForDateRange(values) {
        return buildDateFacet(this.bindings.engine, {
            options: {
                facetId: this.facetId,
                field: this.field,
                currentValues: values,
                generateAutomaticRanges: false,
                sortCriteria: this.sortCriteria,
                filterFacetCount: this.filterFacetCount,
                injectionDepth: this.injectionDepth
            }
        });
    }
    initializeFilter() {
        return buildDateFilter(this.bindings.engine, {
            options: {
                facetId: `${this.facetId}_input`,
                field: this.field
            }
        });
    }
    render() {
        return html`${when(this.timeframeFacetCommon, ()=>this.timeframeFacetCommon.render({
                hasError: this.searchStatusState.hasError,
                firstSearchExecuted: this.searchStatusState.firstSearchExecuted,
                isCollapsed: this.isCollapsed,
                headerFocus: this.focusTarget,
                onToggleCollapse: ()=>{
                    this.isCollapsed = !this.isCollapsed;
                    return this.isCollapsed;
                }
            }), ()=>renderFacetPlaceholder({
                props: {
                    numberOfValues: 5,
                    isCollapsed: this.isCollapsed
                }
            }))}`;
    }
    constructor(){
        super(), this.label = 'no-label', this.field = 'date', this.withDatePicker = false, this.isCollapsed = false, this.headingLevel = 0, this.filterFacetCount = true, this.injectionDepth = 1000, this.sortCriteria = 'descending', this.handleDateInputApply = ()=>{
            if (this.facetId) this.bindings.engine.dispatch(loadDateFacetSetActions(this.bindings.engine).deselectAllDateFacetValues(this.facetId));
        };
        new ValidatePropsController(this, ()=>({
                injectionDepth: this.injectionDepth,
                headingLevel: this.headingLevel,
                sortCriteria: this.sortCriteria
            }), AtomicInsightTimeframeFacet.propsSchema, false);
    }
}
AtomicInsightTimeframeFacet.propsSchema = new Schema({
    injectionDepth: new NumberValue({
        min: 0,
        required: false
    }),
    headingLevel: new NumberValue({
        min: 0,
        max: 6,
        required: false
    }),
    sortCriteria: new StringValue({
        constrainTo: [
            'ascending',
            'descending'
        ],
        required: false
    })
});
AtomicInsightTimeframeFacet.styles = facet_common_tw_css;
_ts_decorate([
    property({
        reflect: true
    })
], AtomicInsightTimeframeFacet.prototype, "label", void 0);
_ts_decorate([
    property({
        reflect: true
    })
], AtomicInsightTimeframeFacet.prototype, "field", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        converter: booleanConverter,
        attribute: 'with-date-picker'
    })
], AtomicInsightTimeframeFacet.prototype, "withDatePicker", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        converter: booleanConverter,
        attribute: 'is-collapsed'
    })
], AtomicInsightTimeframeFacet.prototype, "isCollapsed", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'heading-level'
    })
], AtomicInsightTimeframeFacet.prototype, "headingLevel", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        converter: booleanConverter,
        attribute: 'filter-facet-count'
    })
], AtomicInsightTimeframeFacet.prototype, "filterFacetCount", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'injection-depth'
    })
], AtomicInsightTimeframeFacet.prototype, "injectionDepth", void 0);
_ts_decorate([
    mapProperty({
        attributePrefix: 'depends-on'
    }),
    _ts_metadata("design:type", "u" < typeof Record ? Object : Record)
], AtomicInsightTimeframeFacet.prototype, "dependsOn", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'sort-criteria'
    }),
    _ts_metadata("design:type", "u" < typeof RangeFacetSortCriterion ? Object : RangeFacetSortCriterion)
], AtomicInsightTimeframeFacet.prototype, "sortCriteria", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'facet-id'
    }),
    _ts_metadata("design:type", String)
], AtomicInsightTimeframeFacet.prototype, "facetId", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightTimeframeFacet.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightTimeframeFacet.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    state(),
    _ts_metadata("design:type", "u" < typeof SearchStatusState ? Object : SearchStatusState)
], AtomicInsightTimeframeFacet.prototype, "searchStatusState", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightTimeframeFacet.prototype, "render", null);
AtomicInsightTimeframeFacet = _ts_decorate([
    customElement('atomic-insight-timeframe-facet'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicInsightTimeframeFacet);
export { AtomicInsightTimeframeFacet };
