import { html, nothing } from "lit";
import { parseDate } from "../../../utils/date-utils.js";
import { getFieldValueCaption } from "../../../utils/field-utils.js";
import { randomID } from "../../../utils/utils.js";
import { shouldDisplayInputForFacetRange } from "./facet-common.js";
import { renderFacetContainer } from "./facet-container/facet-container.js";
import { renderFacetHeader } from "./facet-header/facet-header.js";
import { renderFacetPlaceholder } from "./facet-placeholder/facet-placeholder.js";
import { renderFacetValueLabelHighlight } from "./facet-value-label-highlight/facet-value-label-highlight.js";
import { renderFacetValueLink } from "./facet-value-link/facet-value-link.js";
import { renderFacetValuesGroup } from "./facet-values-group/facet-values-group.js";
import { initializePopover } from "./popover/popover-type.js";
import "../atomic-facet-date-input/atomic-facet-date-input.js";
import "../atomic-timeframe/atomic-timeframe.js";
class TimeframeFacetCommon {
    get determineFacetId() {
        if (this.props.facetId) return this.props.facetId;
        if (this.props.bindings.store.state.dateFacets[this.props.field]) return randomID(`${this.props.field}_`);
        return this.props.field;
    }
    get enabled() {
        return this.facetForDateRange?.state.enabled ?? this.filter?.state.enabled ?? true;
    }
    get valuesToRender() {
        return this.facetForDateRange?.state.values.filter((value)=>value.numberOfResults || 'idle' !== value.state) || [];
    }
    get shouldRenderValues() {
        return !this.hasInputRange && !!this.valuesToRender.length;
    }
    get shouldRenderFacet() {
        return this.shouldRenderInput || this.shouldRenderValues;
    }
    get shouldRenderInput() {
        return shouldDisplayInputForFacetRange({
            hasInput: this.props.withDatePicker,
            hasInputRange: this.hasInputRange,
            searchStatusState: this.props.getSearchStatusState(),
            facetValues: this.facetForDatePicker?.state?.values || []
        });
    }
    get hasValues() {
        if (this.facetForDatePicker?.state.values.length) return true;
        return !!this.valuesToRender.length;
    }
    get numberOfSelectedValues() {
        if (this.filter?.state?.range) return 1;
        return this.facetForDateRange?.state.values.filter(({ state })=>'selected' === state).length || 0;
    }
    get hasInputRange() {
        return !!this.filter?.state.range;
    }
    get currentValues() {
        return this.manualTimeframes.map(({ period, amount, unit })=>'past' === period ? this.props.buildDateRange({
                start: {
                    period,
                    unit,
                    amount
                },
                end: {
                    period: 'now'
                }
            }) : this.props.buildDateRange({
                start: {
                    period: 'now'
                },
                end: {
                    period,
                    unit,
                    amount
                }
            }));
    }
    disconnectedCallback() {
        if (this.props.host.isConnected) return;
        this.facetForDateRangeDependenciesManager?.stopWatching();
        this.facetForDatePickerDependenciesManager?.stopWatching();
        this.filterDependenciesManager?.stopWatching();
    }
    get isHidden() {
        return !this.shouldRenderFacet || !this.enabled;
    }
    registerFacetToStore() {
        const facetInfo = {
            label: ()=>this.props.bindings.i18n.t(this.props.label),
            facetId: this.facetId,
            element: this.props.host,
            isHidden: ()=>this.isHidden
        };
        this.props.bindings.store.registerFacet('dateFacets', {
            ...facetInfo,
            format: (value)=>this.formatFacetValue(value)
        });
        initializePopover(this.props.host, {
            ...facetInfo,
            hasValues: ()=>this.hasValues,
            numberOfActiveValues: ()=>this.numberOfSelectedValues
        });
        if (this.filter) this.props.bindings.store.state.dateFacets[this.filter.state.facetId] = this.props.bindings.store.state.dateFacets[this.facetId];
    }
    getManualTimeframes() {
        return Array.from(this.props.host.querySelectorAll('atomic-timeframe')).map(({ label, amount, unit, period })=>({
                label,
                amount,
                unit,
                period
            }));
    }
    formatFacetValue(facetValue) {
        try {
            const startDate = this.props.deserializeRelativeDate(facetValue.start);
            const relativeDate = 'past' === startDate.period ? startDate : this.props.deserializeRelativeDate(facetValue.end);
            const timeframe = this.getManualTimeframes().find((timeframe)=>timeframe.period === relativeDate.period && timeframe.unit === relativeDate.unit && timeframe.amount === relativeDate.amount);
            if (timeframe?.label) return getFieldValueCaption(this.props.field, timeframe.label, this.props.bindings.i18n);
            return this.props.bindings.i18n.t(`${relativeDate.period}-${relativeDate.unit}`, {
                count: relativeDate.amount
            });
        } catch (_error) {
            return this.props.bindings.i18n.t('to', {
                start: parseDate(facetValue.start).format('YYYY-MM-DD'),
                end: parseDate(facetValue.end).format('YYYY-MM-DD')
            });
        }
    }
    renderValues() {
        return this.renderValuesContainer(this.valuesToRender.map((value)=>this.renderValue(value)));
    }
    renderValue(facetValue) {
        const displayValue = this.formatFacetValue(facetValue);
        const isSelected = 'selected' === facetValue.state;
        const isExcluded = 'excluded' === facetValue.state;
        return renderFacetValueLink({
            props: {
                displayValue,
                isSelected,
                numberOfResults: facetValue.numberOfResults,
                i18n: this.props.bindings.i18n,
                onClick: ()=>this.facetForDateRange.toggleSingleSelect(facetValue)
            }
        })(renderFacetValueLabelHighlight({
            props: {
                displayValue,
                isSelected,
                isExcluded
            }
        }));
    }
    renderValuesContainer(children) {
        return renderFacetValuesGroup({
            props: {
                i18n: this.props.bindings.i18n,
                label: this.props.label
            }
        })(html`<ul class="mt-3" part="values">
      ${children}
    </ul>`);
    }
    renderHeader(isCollapsed, headerFocus, onToggleCollapse) {
        return renderFacetHeader({
            props: {
                i18n: this.props.bindings.i18n,
                label: this.props.label,
                onClearFilters: ()=>{
                    headerFocus.focusAfterSearch();
                    if (this.filter?.state.range) return void this.filter?.clear();
                    this.facetForDateRange?.deselectAll();
                },
                numberOfActiveValues: this.numberOfSelectedValues,
                isCollapsed,
                headingLevel: this.props.headingLevel,
                onToggleCollapse,
                headerRef: (el)=>headerFocus.setTarget(el)
            }
        });
    }
    renderDateInput() {
        return html`<atomic-facet-date-input
      .min=${this.props.min}
      .max=${this.props.max}
      .label=${this.props.label}
      .facetId=${this.filter.state.facetId}
      .inputRange=${this.filter.state.range}
      @atomic-date-input-apply=${(event)=>{
            this.filter.setRange({
                start: event.detail.start,
                end: event.detail.end
            });
        }}
    ></atomic-facet-date-input>`;
    }
    render({ hasError, firstSearchExecuted, isCollapsed, headerFocus, onToggleCollapse }) {
        if (hasError || !this.enabled) return nothing;
        if (!firstSearchExecuted) return renderFacetPlaceholder({
            props: {
                numberOfValues: this.currentValues.length,
                isCollapsed
            }
        });
        if (!this.shouldRenderFacet) return nothing;
        return renderFacetContainer()(html`${this.renderHeader(isCollapsed, headerFocus, onToggleCollapse)}
      ${!isCollapsed ? html`${this.shouldRenderValues ? this.renderValues() : nothing}
          ${this.shouldRenderInput ? this.renderDateInput() : nothing}` : nothing}`);
    }
    constructor(props){
        this.props = props;
        this.manualTimeframes = [];
        this.facetId = this.determineFacetId;
        this.props.setFacetId(this.facetId);
        this.manualTimeframes = this.getManualTimeframes();
        if (this.manualTimeframes.length > 0) this.facetForDateRange = this.props.initializeFacetForDateRange(this.currentValues);
        if (this.props.withDatePicker) {
            this.facetForDatePicker = this.props.initializeFacetForDatePicker();
            this.facetForDatePickerDependenciesManager = this.props.buildDependenciesManager(this.facetForDatePicker.state.facetId);
            this.filter = this.props.initializeFilter();
        }
        if (this.facetForDateRange) this.facetForDateRangeDependenciesManager = this.props.buildDependenciesManager(this.facetForDateRange?.state.facetId);
        if (this.filter) this.filterDependenciesManager = this.props.buildDependenciesManager(this.filter?.state.facetId);
        this.registerFacetToStore();
    }
}
export { TimeframeFacetCommon };
