import { useState } from 'react';
import { useWixPatternsRouter } from '../providers/WixPatternsRouterProvider';
import { getCollectionComponentUniqueId } from '../utils/getCollectionComponentUniqueId';
import { QueryCache, } from '@wix/bex-core';
import { useSyncCollectionOnEntityCreate } from './useSyncCollectionOnEntityCreate';
import { useSyncCollectionOnEntityUpdate } from './useSyncCollectionOnEntityUpdate';
import { useWixPatternsContainer } from '@wix/bex-core/react';
const getCachedState = ({ shouldResetCache, uniqueId, router, container, }) => {
    const resetCache = shouldResetCache?.({
        router,
        uniqueId,
    });
    if (resetCache) {
        router?.stateRefs.delete(uniqueId);
        container.queryCache = new QueryCache();
    }
    return router?.stateRefs.get(uniqueId);
};
export function useOptionalCachedState(createState, { getCollectionsToUpdate, shouldResetCache, } = {}) {
    const container = useWixPatternsContainer();
    const router = useWixPatternsRouter();
    const [maybeNewState] = useState(() => createState());
    const uniqueId = getCollectionComponentUniqueId(maybeNewState);
    const [cachedState] = useState(getCachedState({ router, uniqueId, shouldResetCache, container }));
    useSyncCollectionOnEntityCreate(cachedState, getCollectionsToUpdate);
    useSyncCollectionOnEntityUpdate(cachedState, getCollectionsToUpdate);
    const [state] = useState(() => {
        if (router) {
            router.isUsingCache = !!cachedState;
        }
        if (cachedState) {
            return cachedState;
        }
        router?.saveState(maybeNewState);
        return maybeNewState;
    });
    return state;
}
//# sourceMappingURL=useOptionalCachedState.js.map