import { useContext, useEffect, useMemo } from 'react';
import { ConfigContext } from '../../ConfigProvider';
import { useScrollManagement } from '../../useScrollManagement';
import { useStickyButton } from '../../useStickyButton';
import { useViewportType } from '../../useViewportType';
import { classNames } from '../../utils/classNames';
import { cardGridClassnames, OVERSCAN, VIRTUOSO_CONTAINER_ID, } from '../constants';
export const useLogic = ({ list, isLoading, isError, errorMsg, errorImgSrc, scrollRef, skeleton, onRetry, endOfScrollMsg, isEndReached, onLoadMore, noDataImgSrc, defineCard, desktopCardWidth, }) => {
    const { imagesMap } = useContext(ConfigContext);
    const { isMobile } = useViewportType();
    useEffect(() => {
        if (isMobile && scrollRef?.current) {
            scrollRef.current.style.backgroundColor = 'unset';
            scrollRef.current.style.padding = 'unset';
        }
    }, [isMobile]);
    const contentStateProps = useMemo(() => {
        const isNoData = !list?.length;
        return {
            isLoading: isNoData && isLoading,
            isError: isNoData && isError,
            loadingTitle: 'Загрузка данных',
            errorState: {
                imgAlt: 'Что-то пошло не так',
                errorList: [errorMsg || ''],
                imgSrc: errorImgSrc || imagesMap.defaultErrorImgSrc,
                onRetry,
            },
        };
    }, [list, isLoading, isError, errorMsg, errorImgSrc, imagesMap]);
    const { scrollParent, recalculateVerticalScroll, handleEndReach, isEndReachedWithScroll, } = useScrollManagement({
        scrollRef,
        isEndReached,
        onLoadMore,
        virtuosoId: VIRTUOSO_CONTAINER_ID,
    });
    const { virtuoso, isStickyButtonActive, handleRangeChanged: propsHandleRangeChanged, handleScrollToTop, } = useStickyButton(scrollRef);
    const handleRangeChanged = (range) => {
        recalculateVerticalScroll();
        propsHandleRangeChanged(range);
    };
    const classnames = useMemo(() => classNames(cardGridClassnames.root, {
        [cardGridClassnames.loading]: isLoading,
    }), [isLoading]);
    return {
        contentStateProps,
        desktopCardWidth,
        virtuosoProps: {
            id: VIRTUOSO_CONTAINER_ID,
            style: { height: '100%' },
            ref: virtuoso,
            overscan: OVERSCAN,
            rangeChanged: handleRangeChanged,
            endReached: handleEndReach,
        },
        footerProps: {
            isError,
            isEndReached: isEndReachedWithScroll,
            onRetry,
            endOfScrollMsg,
            isLoading,
        },
        onTopButtonProps: {
            isActive: isStickyButtonActive,
            handleScrollToTop,
            scrollRef,
        },
        isMobile,
        scrollParent,
        skeleton,
        list,
        noDataImgSrc,
        defineCard,
        classnames,
    };
};
