import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/*
* Copyright (c) 2020-present SMC Treviso s.r.l. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
import React from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "react-query";
import { css } from "styled-components";
import { useOpenK9Client } from "./client";
import { FilterCategoryDynamicMemo, } from "./FilterCategoryDynamic";
import { Logo } from "./Logo";
import CustomSkeleton from "./Skeleton";
import { useInfiniteResults } from "./ResultListPagination";
function Filters({ searchQuery, onAddFilterToken, onRemoveFilterToken, sort, preFilters, language, sortAfterKey, numberItems, isDynamicElement, noResultMessage, isActiveSkeleton, skeletonCategoryCustom, placeholder, iconCustom, haveSearch = true, state, dynamicFilters = true, overrideSearchWithCorrection, isOpenFilter = false, setOverrideSearchWithCorrection, }) {
    const suggestionCategories = useSuggestionCategories();
    const [lastSearchQueryWithResults, setLastSearchQueryWithResults] = React.useState(searchQuery);
    const [offset, elementForPage] = state.range;
    const infiniteResults = useInfiniteResults(state, searchQuery, sort, language, sortAfterKey, elementForPage, offset, overrideSearchWithCorrection, setOverrideSearchWithCorrection, dynamicFilters);
    const isPreviousData = infiniteResults?.isPreviousData ?? false;
    React.useEffect(() => {
        if (!isPreviousData) {
            setLastSearchQueryWithResults(searchQuery);
        }
    }, [isPreviousData, searchQuery]);
    return (_jsxs(_Fragment, { children: [suggestionCategories.data?.length === 0 && !preFilters && (_jsxs("div", { className: "openk9-filters-container-internal-no-filters", css: css `
            color: var(--openk9-embeddable-search--secondary-text-color);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 50vh;
          `, children: [_jsx(Logo, { size: 100 }), _jsx("h4", { children: "No Filters " })] })), preFilters, suggestionCategories.data?.map((suggestionCategory, index) => (_jsx(React.Suspense, { fallback: skeletonCategoryCustom && isActiveSkeleton && skeletonCategoryCustom, children: _jsx(FilterCategoryDynamicMemo, { suggestionCategoryName: translateSuggesionCategoryName({
                        names: suggestionCategory.translationMap,
                        language: language,
                        defaultValue: suggestionCategory.name,
                    }), suggestionCategoryId: suggestionCategory.id, tokens: lastSearchQueryWithResults, onAdd: onAddFilterToken, onRemove: onRemoveFilterToken, multiSelect: suggestionCategory?.multiSelect, searchQuery: searchQuery, language: language, numberItems: numberItems, isDynamicElement: isDynamicElement, noResultMessage: noResultMessage, placeholder: placeholder, iconCustom: iconCustom, haveSearch: haveSearch, isOpenFilter: isOpenFilter }, suggestionCategory.id) }, index)))] }));
}
export const FiltersMemo = React.memo(Filters);
function useSuggestionCategories() {
    const client = useOpenK9Client();
    return useQuery(["suggestion-categories"], async ({ queryKey }) => {
        const result = await client.getSuggestionCategories();
        return result;
    }, {
        suspense: true,
        keepPreviousData: true,
    });
}
export function CreateLabel({ label, idValue, action, svgIcon, classN = "", gap = "4px", sizeHeight = "15px", sizeFont = "12px", marginOfSvg = "0px", marginRigthOfSvg = "0px", hasBorder = true, svgIconRight, padding = "12px 8px", fontWeightLabel = "500", disabled = false, widthLabel, ariaLabel = "", colorLabel = "var(--openk9-embeddable-search--secondary-active-color)", }) {
    return (_jsxs("button", { "aria-label": ariaLabel || "", id: idValue || "", disabled: false, className: `openk9-create-label-container-wrapper ${classN}`, css: css `
        display: flex;
        justify-content: center;
        align-items: center;
        padding: ${padding};
        gap: ${gap};
        height: ${sizeHeight};
        background: #ffffff;
        border: ${hasBorder
            ? "1px solid  var(--openk9-embeddable-search--secondary-active-color);"
            : ""};
        border-radius: 20px;
        white-space: nowrap;
        cursor: pointer;
        color: ${colorLabel};
        font-size: ${sizeFont};
        width: ${widthLabel};
      `, onClick: action, children: [svgIcon, _jsx("span", { className: "openk9-create-label-container-internal-space", css: css `
          margin-left: ${marginOfSvg};
          margin-right: ${marginRigthOfSvg};
          font-weight: ${fontWeightLabel};
        `, children: label }), svgIconRight] }));
}
function mergeAndSortArrays(sortedArray, unsortedArray) {
    const mergedArray = [...sortedArray];
    for (const element of unsortedArray) {
        if (!sortedArray.includes(element)) {
            mergedArray.push(element);
        }
    }
    mergedArray.sort((a, b) => a.localeCompare(b));
    return mergedArray;
}
function translateSuggesionCategoryName({ names, language, defaultValue, }) {
    const desiredKey = "name." + language;
    if (names && names.hasOwnProperty(desiredKey)) {
        return names[desiredKey];
    }
    return defaultValue;
}
export function SkeletonFilters() {
    return (_jsxs("div", { className: "container-openk9-skeleton", css: css `
        width: 100%;
      `, children: [_jsx("div", { className: "container-openk9-skeleton-wrapper", css: css `
          padding-inline: 16px;
        `, children: _jsx(CustomSkeleton, {}) }), _jsx("div", { className: "openk9-filters-container-internal", css: css `
          padding-inline: 16px;
          padding-top: 16px;
        `, children: _jsxs("div", { css: css `
            display: flex;
            flex-direction: column;
            gap: 10px;
          `, children: [_jsx(CustomSkeleton, {}), new Array(5).fill(null).map((_, index) => (_jsxs("div", { css: css `
                display: flex;
                gap: 10px;
                width: 100%;
              `, children: [_jsx(CustomSkeleton, { width: "20px" }), _jsx(CustomSkeleton, { containerMax: true })] }, index)))] }) })] }));
}
function SkeletonCategory() {
    const { t } = useTranslation();
    return (_jsx("div", { className: "openk9-filters-container-internal", css: css `
        padding-inline: 16px;
        padding-top: 16px;
      `, children: _jsxs("div", { css: css `
          display: flex;
          flex-direction: column;
          gap: 10px;
        `, children: [_jsx(CustomSkeleton, {}), new Array(5).fill(null).map((_, index) => (_jsxs("div", { css: css `
              display: flex;
              gap: 10px;
              width: 100%;
            `, children: [_jsx(CustomSkeleton, { width: "20px" }), _jsx(CustomSkeleton, { containerMax: true })] }, index)))] }) }));
}
