import { jsx as _jsx, jsxs as _jsxs } 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 { css } from "styled-components";
import { OverlayScrollbarsComponent } from "overlayscrollbars-react";
import { useOpenK9Client } from "./client";
import { useInfiniteQuery, useQuery, } from "react-query";
import { useInfiniteResults } from "./ResultList";
import { Logo } from "./Logo";
import { createSuggestion, haveSomeValue, mergeAndSortObjects, } from "./FilterCategoryDynamic";
import { useTranslation } from "react-i18next";
import { mapSuggestionToSearchToken } from "./FilterCategory";
import { capitalize } from "lodash";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faChevronDown } from "@fortawesome/free-solid-svg-icons/faChevronDown";
import { faChevronUp } from "@fortawesome/free-solid-svg-icons/faChevronUp";
import { TrashSvg } from "../svgElement/TrashSvg";
import { AddFiltersSvg } from "../svgElement/AddFiltersSvg";
import { ArrowDownSvg } from "../svgElement/ArrowDownSvg";
function FiltersHorizontal({ searchQuery, onConfigurationChange, onConfigurationChangeExt, sort, dynamicFilters, language, sortAfterKey, numberOfResults, numberResultOfFilters, isDynamicElement, selectionsDispatch, refButton, callbackReset, callbackSubmit, memoryResults, }) {
    const suggestionCategories = useSuggestionCategories();
    const [lastSearchQueryWithResults, setLastSearchQueryWithResults] = React.useState(searchQuery);
    const { data, isPreviousData } = useInfiniteResults(searchQuery, sort, language, sortAfterKey, numberOfResults, memoryResults);
    React.useEffect(() => {
        if (!isPreviousData) {
            setLastSearchQueryWithResults(searchQuery);
        }
    }, [isPreviousData, searchQuery]);
    const [filterSelect, setFilterSelect] = React.useState(searchQuery);
    const handleCheckboxChange = (event, token) => {
        const isChecked = event.target.checked;
        const newFilter = {
            ...token,
            attributeName: [token.values],
        };
        if (isChecked) {
            setFilterSelect([...filterSelect, newFilter]);
        }
        else {
            setFilterSelect(filterSelect.map((t) => {
                if (t.values && newFilter) {
                    const filteredValues = t.values.filter((value) => newFilter?.values && value !== newFilter.values[0]);
                    return { ...t, values: filteredValues };
                }
                else {
                    return t;
                }
            }));
        }
    };
    let isPresent = true; //per sapere se Ã¨ presente almeno un filtro all'interno di una qualsiasi suggestion
    const { t } = useTranslation();
    return (_jsxs(React.Fragment, { children: [_jsxs(OverlayScrollbarsComponent, { className: "openk9-filter-overlay-scrollbars", css: css `
          overflow-y: auto;
          position: relative;
          border-radius: 8px;
        `, children: [suggestionCategories?.data?.map((suggestion, index) => {
                        const suggestions = useInfiniteSuggestions(isDynamicElement, lastSearchQueryWithResults, dynamicFilters, suggestion.id, language, numberResultOfFilters);
                        const suggestionFilters = MemoizedCreateSuggestion(index, suggestion, suggestions);
                        if (suggestionFilters)
                            isPresent = false;
                        return suggestionFilters;
                    }), isPresent && (_jsx("div", { className: "openk9-filter-horizontal-noFilters", children: _jsx(NoFilters, {}) }))] }), !isPresent && (_jsx("div", { css: css `
            @media (max-width: 480px) {
              margin-top: 5px;
              border: 0.5px solid rgba(128, 128, 128, 0.48);
            }
          ` })), !isPresent && (_jsxs("div", { className: "openk9-filter-horizontal-container-submit", css: css `
            display: flex;
            justify-content: flex-end;
            @media (max-width: 480px) {
              padding-inline: 20px;
              flex-direction: column;
              gap: 15px;
            }
          `, children: [_jsxs("button", { className: "openk9-filter-horizontal-submit openk9-filter-button-mobile-remove", disabled: filterSelect.every((token) => !token.values || token.values.length === 0), "aria-label": "rimuovi filtri", css: css `
              font-size: smaller;
              height: 52px;
              padding: 8px 12px;
              white-space: nowrap;
              border: 1px solid #d6012e;
              background-color: #d6012e;
              border-radius: 5px;
              color: white;
              font-weight: 600;
              cursor: pointer;
              display: flex;
              align-items: center;
              gap: 3px;
              &:disabled {
                opacity: 0.6;
                cursor: not-allowed;
              }
              @media (max-width: 480px) {
                background: white;
                border: 1px solid #d6012e;
                width: 100%;
                height: auto;
                margin-top: 20px;
                color: black;
                border-radius: 50px;
                display: flex;
                justify-content: center;
                color: var(--red-tones-500, #c0272b);
                text-align: center;
                font-size: 16px;
                font-style: normal;
                font-weight: 700;
                line-height: normal;
                align-items: center;
              }
            `, onClick: () => {
                            onConfigurationChange({ filterTokens: [] });
                            onConfigurationChangeExt && onConfigurationChangeExt();
                            selectionsDispatch({ type: "reset-filters" });
                            setFilterSelect([]);
                            if (callbackReset)
                                callbackReset();
                            if (refButton && refButton.current)
                                refButton.current.focus();
                        }, children: [_jsx("div", { children: t("remove-filters") }), _jsx(TrashSvg, { size: "18px" })] }), _jsxs("button", { className: `openk9-filter-horizontal-submit openk9-filter-button-mobile-apply ${filterSelect.length === 0 ? "openk9-button-disabled" : ""}`, disabled: filterSelect.every((token) => !token.values || token.values.length === 0), "aria-label": "applica filtri", css: css `
              font-size: smaller;
              height: 52px;
              padding: 8px 12px;
              white-space: nowrap;
              border: 1px solid #d6012e;
              background-color: #d6012e;
              border-radius: 5px;
              color: white;
              font-weight: 600;
              cursor: pointer;
              display: flex;
              align-items: center;
              gap: 3px;
              @media (max-width: 480px) {
                background: #d6012e;
                border: 1px solid #d6012e;
                width: 100%;
                height: auto;
                margin-top: 20px;
                color: white;
                border-radius: 50px;
                display: flex;
                justify-content: center;
                text-align: center;
                font-size: 16px;
                font-style: normal;
                font-weight: 700;
                line-height: normal;
              }
              &:disabled {
                opacity: 0.6;
                cursor: not-allowed;
              }
            `, onClick: () => {
                            onConfigurationChange({ filterTokens: filterSelect });
                            onConfigurationChangeExt && onConfigurationChangeExt();
                            if (callbackSubmit)
                                callbackSubmit();
                            if (refButton && refButton.current)
                                refButton.current.focus();
                        }, children: [_jsx("div", { children: t("add-filters") || "Add Filters" }), _jsx("div", { children: _jsx(AddFiltersSvg, { size: "22px" }) })] })] }))] }));
    function MemoizedCreateSuggestion(index, suggestion, suggestions) {
        return CreateSuggestion(index, suggestion, suggestions);
    }
    function CreateSuggestion(index, suggestion, suggestions) {
        const [isOpen, setIsOpen] = React.useState(true);
        const resultValue = suggestions.data?.pages || [];
        const filters = mergeAndSortObjects(resultValue, searchQuery, suggestion.id);
        if (filters.length === 0)
            return null;
        return (_jsx(React.Fragment, { children: filters.length !== 0 && (_jsxs(React.Fragment, { children: [_jsxs("fieldset", { css: css `
                border: 0;
              `, children: [_jsxs("div", { css: css `
                  margin-top: 20px;
                  margin-bottom: 20px;
                  @media (max-width: 480px) {
                    display: flex;
                    justify-content: space-between;
                    margin-left: 16px;
                    margin-bottom: 20px;
                  }
                `, children: [_jsx("div", { className: "openk9-filters-horizontal-category", css: css `
                    color: #525258;
                    font-weight: 600;
                    ::first-letter {
                      text-transform: capitalize;
                    }
                    @media (max-width: 480px) {
                      color: var(--openk9-embeddable-tabs--primary-color);
                      font-weight: 700;
                    }
                  `, children: _jsx("legend", { children: suggestion.name }) }), _jsx("button", { "aria-label": isOpen ? "chiudi i filtri" : "apri i filtri", className: "openk9-close-filters", css: css `
                    margin-right: 16px;
                    background: inherit;
                    border: none;
                    @media (min-width: 480px) {
                      display: none;
                    }
                  `, onClick: () => {
                                            setIsOpen(!isOpen);
                                        }, children: _jsx(FontAwesomeIcon, { icon: isOpen ? faChevronDown : faChevronUp, css: css `
                      color: var(
                        --openk9-embeddable-search--secondary-text-color
                      );
                      margin-right: 6px;
                    ` }) })] }), _jsx(GridContainer, { children: isOpen &&
                                    filters.map((token, index) => {
                                        const asSearchToken = mapSuggestionToSearchToken(token, true);
                                        const checked = filterSelect.some((element) => {
                                            return (element.values &&
                                                haveSomeValue(element.values, [token.value]) &&
                                                "goToSuggestion" in element &&
                                                element.suggestionCategoryId ===
                                                    token.suggestionCategoryId);
                                        });
                                        return (_jsx(React.Fragment, { children: _jsxs("div", { className: `openk9-filter-horizontal-container-input-value ${checked ? "check-container" : "not-check-container"}`, css: css `
                            overflow: hidden;
                            text-overflow: ellipsis;
                            color: ${checked ? "#d6012e" : "black"};
                            display: flex;
                            align-items: flex-start;
                            @media (max-width: 480px) {
                              margin-left: 15px;
                              margin-right: 15px;
                            }
                          `, children: [_jsx("input", { id: "filter-horizontal " +
                                                            index +
                                                            " " +
                                                            suggestion.name, className: `custom-checkbox openk9-filter-horizontal-input  ${checked
                                                            ? "checked-checkbox"
                                                            : "not-checked-checkbox"}`, type: "checkbox", checked: checked, onChange: (event) => handleCheckboxChange(event, asSearchToken), css: css `
                              width: 14px;
                              appearance: none;
                              min-width: 15px;
                              min-height: 15px;
                              border-radius: 4px;
                              border: 2px solid #ccc;
                              background-color: ${checked
                                                            ? "var(--openk9-embeddable-search--secondary-active-color)"
                                                            : "#fff"};
                              background-size: 100%;
                              background-position: center;
                              background-repeat: no-repeat;
                              cursor: pointer;
                              margin-right: 10px;
                            ` }), _jsx("label", { htmlFor: "filter-horizontal " +
                                                            index +
                                                            " " +
                                                            suggestion.name, children: asSearchToken?.values &&
                                                            capitalize(asSearchToken?.values[0]) })] }) }, index));
                                    }) })] }), suggestions.hasNextPage && (_jsx("div", { className: "openk9-container-load-more", css: css `
                  text-align: center;
                  width: 100%;
                  display: flex;
                  margin-left: 12px;
                  margin-top: 10px;
                  justify-content: center;
                  @media (max-width: 480px) {
                    margin-top: 15px;
                  }
                `, children: _jsxs("button", { className: "openk9-load-more-button horizontal-filter-load-more", "aria-label": t("load-more-filter") || "load more filters", css: css `
                    background: inherit;
                    color: var(--openk9-embeddable-search--primary-color);
                    font-size: 14px;
                    font-style: normal;
                    font-weight: 700;
                    line-height: normal;
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    cursor: pointer;
                    padding: 8px 16px;
                    border: 1px solid
                      var(--openk9-embeddable-search--primary-color);
                    border-radius: 20px;
                  `, onClick: () => {
                                suggestions.fetchNextPage();
                            }, children: [t("load-more") || "Load More", _jsx(ArrowDownSvg, { size: "18px" })] }) }))] })) }, index));
    }
}
export const FiltersHorizontalMemo = React.memo(FiltersHorizontal);
const GridContainer = ({ children }) => (_jsx("div", { className: "openk9-filters-horizontal-container", css: css `
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      grid-gap: 15px;
      grid-auto-rows: auto;
      margin-bottom: 50px;
      @media (max-width: 480px) {
        grid-template-columns: repeat(1, 1fr);
        overflow: auto;
        margin-bottom: 20px;
      }
    `, children: children }));
function useSuggestionCategories() {
    const client = useOpenK9Client();
    return useQuery(["suggestion-categories"], async ({ queryKey }) => {
        const result = await client.getSuggestionCategories();
        return result;
    }, {
        suspense: true,
        keepPreviousData: true,
    });
}
export function useInfiniteSuggestions(isDynamicElement, searchQueryParams, dynamicFilters, suggestionCategoryId, language, numberResultOfFilters) {
    const pageSize = numberResultOfFilters ? numberResultOfFilters : 8;
    const client = useOpenK9Client();
    const searchQuery = false
        ? searchQueryParams
        : createSuggestion(searchQueryParams, isDynamicElement);
    const suggestionCategories = useInfiniteQuery(["suggestions", searchQuery, suggestionCategoryId, false], async ({ queryKey: [_, searchQuery, suggestionCategoryId], pageParam }) => {
        if (!searchQuery)
            throw new Error();
        const result = await client.getSuggestions({
            searchQuery,
            range: [0, pageSize + 1],
            afterKey: pageParam,
            suggestionCategoryId: suggestionCategoryId,
            order: "desc",
            language: language,
        });
        return {
            result: result.result,
            afterKey: result.afterKey,
        };
    }, {
        enabled: searchQuery !== null,
        keepPreviousData: true,
        getNextPageParam(lastPage, pages) {
            if (!lastPage.afterKey)
                return undefined;
            if (pages[pages.length - 1].result.length < pageSize)
                return undefined;
            return lastPage.afterKey;
        },
        suspense: true,
    });
    return suggestionCategories;
}
export function NoFilters() {
    const { t } = useTranslation();
    return (_jsx("div", { children: _jsxs("div", { className: "openk9-filter-category-no-results-is-open", css: css `
          color: var(--openk9-embeddable-search--secondary-text-color);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          margin-top: 18px;
          margin-left: 10px;
        `, children: [_jsx(Logo, { size: 100 }), _jsxs("h4", { children: [t("no-filters"), " "] })] }) }));
}
export function isChecked(values, value) {
    return values.includes(value);
}
