import { jsx as _jsx, Fragment as _Fragment, 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 { useTranslation } from "react-i18next";
import { useInfiniteQuery } from "react-query";
import { css } from "styled-components";
import { ResultTitleTwo } from "../renderer-components";
import { Logo } from "./Logo";
import { ResultMemo } from "./Result";
import CustomSkeleton from "./Skeleton";
import { useOpenK9Client, } from "./client";
import { useRenderers } from "./useRenderers";
import { useRange, } from "./useRange";
function ResultsPagination({ state, dispatch, onDetail, searchQuery, sort, setSortResult, isMobile, setDetailMobile, overChangeCard = false, language, sortAfterKey, setTotalResult, pageSize = 10, initialPage = 0, callback, CustomNoResults, backgroundSkeleton, }) {
    const renderers = useRenderers();
    if (!renderers)
        return null;
    const bootstrappedRef = React.useRef(false);
    React.useEffect(() => {
        if (bootstrappedRef.current)
            return;
        const size = pageSize ?? state.range[1];
        const page = initialPage ?? 0;
        dispatch({ type: "set-range", range: [page * size, size] });
        bootstrappedRef.current = true;
    }, [initialPage, pageSize, dispatch, state.range]);
    return (_jsx(React.Suspense, { fallback: _jsx(SkeletonResult, { background: backgroundSkeleton }), children: _jsx(InfiniteResults, { state: state, setTotalResult: setTotalResult, renderers: renderers, searchQuery: searchQuery, onDetail: onDetail, setDetailMobile: setDetailMobile, sort: sort, setSortResult: setSortResult, isMobile: isMobile, overChangeCard: overChangeCard, language: language, sortAfterKey: sortAfterKey, callback: callback, customNoResults: CustomNoResults }) }));
}
export const ResultsPaginationMemo = React.memo(ResultsPagination);
export function InfiniteResults({ state, renderers, searchQuery, onDetail, setDetailMobile, sort, isMobile, overChangeCard = false, language, sortAfterKey, setTotalResult, callback, customNoResults, dynamicFilters = true, }) {
    const [offset, elementForPage] = state.range;
    const { setNumberOfResults, setCorrection, overrideSearchWithCorrection, setOverrideSearchWithCorrection, } = useRange();
    const results = useInfiniteResults(state, searchQuery, sort, language, sortAfterKey, elementForPage, offset, overrideSearchWithCorrection, setOverrideSearchWithCorrection, dynamicFilters);
    React.useEffect(() => {
        const total = results?.data?.pages[0]?.total ?? 0;
        setTotalResult(total);
        setNumberOfResults(total);
        setCorrection(results?.data?.pages[0]?.autocorrection);
    }, [results?.data, setTotalResult, setNumberOfResults, setCorrection]);
    return (_jsx("div", { css: css `
        overflow-x: hidden;
      `, className: "scroll", children: results?.data?.pages[0]?.total ?? 0 > 0 ? (_jsx("div", { className: "openk9-infinite-results-container-wrapper", css: css `
            padding-bottom: 16px;
            ::-webkit-scrollbar {
              width: 10px;
            }
            ::-webkit-scrollbar-track {
              box-shadow: inset 0 0 5px grey;
              border-radius: 10px;
            }
            ::-webkit-scrollbar-thumb {
              background: gray;
              border-radius: 10px;
              height: 5px;
            }
            ::-webkit-scrollbar-thumb:hover {
              background: black;
              height: 5px;
            }
          `, children: results?.data?.pages.map((page, pageIndex) => (_jsx(React.Fragment, { children: page.result.map((result, resultIndex) => (_jsx(ResultMemo, { renderers: renderers, result: result, onDetail: onDetail, setDetailMobile: setDetailMobile, isMobile: isMobile, overChangeCard: overChangeCard }, resultIndex))) }, pageIndex))) })) : (_jsx(_Fragment, { children: customNoResults ? customNoResults : _jsx(NoResults, {}) })) }));
}
function NoResults() {
    const { t } = useTranslation();
    return (_jsxs("div", { className: "openk9-no-results-container", css: css `
        color: var(--openk9-embeddable-search--secondary-text-color);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
      `, children: [_jsx(Logo, { size: 128 }), _jsx("h3", { children: t("no-results-were-found") }), _jsx("div", { children: t("try-with-another-query") })] }));
}
export function useInfiniteResults(state, searchQuery, sort, language, sortAfterKey, elementForPage, offset, overrideSearchWithCorrection, setOverrideSearchWithCorrection, dynamicFilters = true) {
    const client = useOpenK9Client();
    const suppressIntermediate = React.useMemo(() => state.text.trim().length > 0 && searchQuery.length === 0, [state.text, searchQuery]);
    if (!dynamicFilters)
        return undefined;
    const remappingSearchQuery = overrideSearchWithCorrection?.isAutocorrection === false
        ? searchQuery.map((token) => token.tokenType === "TEXT" && token.search
            ? { ...token, overrideSearchWithCorrection: false }
            : token)
        : searchQuery;
    const data = useInfiniteQuery([
        "results",
        searchQuery,
        sort,
        language,
        sortAfterKey,
        offset,
        elementForPage,
        overrideSearchWithCorrection?.renderingCorrection,
    ], async ({ queryKey }) => {
        const [, qSearchQuery, qSort, qLanguage, qSortAfterKey, qOffset, qElementForPage,] = queryKey;
        const range = qSortAfterKey === ""
            ? [qOffset, qElementForPage]
            : [0, qElementForPage];
        return client.doSearch({
            range,
            language: qLanguage,
            searchQuery: remappingSearchQuery,
            sort: qSort,
            sortAfterKey: qSortAfterKey || "",
        });
    }, {
        enabled: elementForPage > 0 && !suppressIntermediate,
        keepPreviousData: false,
        suspense: true,
        notifyOnChangeProps: ["isFetching"],
    });
    if (overrideSearchWithCorrection?.isAutocorrection === false) {
        setOverrideSearchWithCorrection?.((ov) => ({
            ...ov,
            isAutocorrection: true,
        }));
    }
    return data;
}
export function SkeletonResult({ background, }) {
    return (_jsx(_Fragment, { children: Array.from({ length: 3 }).map((_, index) => (_jsxs("div", { className: "openk9-embeddable-search--result-container openk9-skeleton-container--result-container", children: [_jsxs("div", { css: css `
              display: flex;
              justify-content: space-between;
              padding: 8px 16px;
            `, children: [_jsx(CustomSkeleton, { width: "80px", backgroundColor: background }), _jsx(CustomSkeleton, { width: "150px", backgroundColor: background })] }), _jsxs("div", { css: css `
              padding: 16px 16px;
              overflow: hidden;
            `, children: [_jsx(ResultTitleTwo, { children: _jsx(CustomSkeleton, { backgroundColor: background }) }), _jsx(CustomSkeleton, { counter: 3, width: "100%", backgroundColor: background })] })] }, index))) }));
}
