import { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { ConfigContext } from '../../ConfigProvider';
import { pageContentClassnames } from '../../PageContent/constants';
import { useViewportType } from '../../useViewportType';
import { useZoom } from '../hooks/useZoom';
import { getPageHeightList } from '../utils';
export const useLogic = ({ file, scrollRef, paginationRef, isFullHeight, isCentered, renderPageRange, isHidePersonalData, isViewerLite, enabledZoom = true, options, ...props }) => {
    const [containerWidth, setContainerWidth] = useState(1);
    const { isMobile } = useViewportType();
    const scrollContainerRef = useRef(null);
    useEffect(() => {
        const el = scrollRef?.current;
        if (!el) {
            return;
        }
        const isPageContentScroll = el.classList.contains(pageContentClassnames.content);
        if (!isPageContentScroll) {
            return;
        }
        el.classList.add(pageContentClassnames.withPdfViewer);
    }, [scrollRef]);
    const { zoomOut, scale, zoomIn, shouldAnimateZoom } = useZoom({
        scrollContainerRef,
        enabledZoom: enabledZoom && !isMobile,
    });
    const [isError, setIsError] = useState(false);
    const [errorData, setErrorData] = useState();
    const [isLoading, setIsLoading] = useState(true);
    const [pdfParams, setPdfParams] = useState(null);
    const [pageHeightList, setPageHeightList] = useState(null);
    const onLoadSuccess = (pdf) => {
        props.onLoadSuccess?.(pdf);
        setPdfParams(pdf);
        setIsLoading(false);
    };
    useEffect(() => {
        if (!pdfParams) {
            return;
        }
        getPageHeightList(pdfParams, containerWidth, scrollRef, renderPageRange, isFullHeight).then((res) => setPageHeightList(res));
    }, [pdfParams, containerWidth]);
    /**
     * Компонент обернут в ContentState. При переключении флага isError происходит mount компонента и запрос отправляется заново
     */
    const onRetry = () => {
        setIsError(false);
    };
    const { imagesMap } = useContext(ConfigContext);
    const errorState = useMemo(() => {
        if (!errorData) {
            return;
        }
        const customErrorState = props?.getErrorState?.(errorData);
        return {
            imgSrc: customErrorState?.errorImgSrc || imagesMap.defaultErrorImgSrc,
            imgAlt: 'Ошибка',
            actions: customErrorState?.actions,
            onRetry: customErrorState?.onRetry || onRetry,
            title: customErrorState?.message || 'Ошибка при загрузке файла',
            errorList: customErrorState?.errorList || ['Попробуйте еще раз'],
        };
    }, [errorData]);
    const onLoadError = (error) => {
        setIsLoading(false);
        setIsError(true);
        setErrorData(error);
        props.onLoadError?.(error);
    };
    const [initialIndex, setInitialIndex] = useState(null);
    const onChangePage = (newPage) => {
        props.onChangePage?.(newPage);
        setInitialIndex(newPage - 1);
    };
    const isRenderList = pageHeightList?.[0] !== 0;
    const loadingPlaceholderTitle = isViewerLite
        ? undefined
        : 'Загрузка данных...';
    const getOptions = useMemo(() => {
        return {
            withCredentials: true,
            ...options,
        };
    }, [options]);
    return {
        documentProps: {
            file,
            options: getOptions,
            onLoadSuccess,
            onLoadError,
            setContainerWidth,
        },
        pageProps: {
            scrollRef,
            onChangePage,
            isHidePersonalData,
            currentPage: Number(initialIndex) + 1,
        },
        pageCount: pdfParams?.numPages || 0,
        pageHeightList,
        isError,
        errorState,
        onRetry,
        paginationRef,
        isLoading,
        initialIndex,
        isRenderList,
        isViewerLite,
        scale,
        zoomIn,
        zoomOut,
        isDisabledZoomOutButton: scale === 1,
        isDisabledZoomInButton: scale === 3,
        scrollContainerRef,
        shouldAnimateZoom,
        loadingPlaceholderTitle,
        enabledZoom,
        isCentered,
    };
};
