import { useEffect, useState } from "react";
import { PageSkeleton } from "@/shared/ui/PageSkeleton.jsx";
import { PageLoadBoundary } from "@/shared/ui/PageLoadBoundary.jsx";

const pageCache = new Map();

export function DeferredPage({ route }) {
    const [Page, setPage] = useState(() => pageCache.get(route.pageKey) || null);

    useEffect(() => {
        let mounted = true;

        if (pageCache.has(route.pageKey)) {
            setPage(() => pageCache.get(route.pageKey));
            return undefined;
        }

        setPage(null);
        route
            .loader()
            .then((component) => {
                pageCache.set(route.pageKey, component);
                if (mounted) {
                    setPage(() => component);
                }
            })
            .catch((error) => {
                if (mounted) {
                    setPage(
                        () =>
                            function DeferredPageLoaderError() {
                                throw error;
                            },
                    );
                }
            });

        return () => {
            mounted = false;
        };
    }, [route]);

    if (!Page) {
        return <PageSkeleton />;
    }

    return (
        <PageLoadBoundary pageKey={route.pageKey}>
            <Page {...(route.props || {})} />
        </PageLoadBoundary>
    );
}
