import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { persistQueryClient } from '@tanstack/react-query-persist-client';
import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useState, useEffect } from 'react';
import type { AsyncPersistRetryer } from '@tanstack/query-async-storage-persister';

const createQueryClient = () => new QueryClient({
    defaultOptions: {
        queries: {
            gcTime: 1000 * 60 * 60 * 24,
            staleTime: 1000 * 60 * 5,
            retry: 2,
        },
    },
});

export function PersistQueryClientProvider({ children }: { children: React.ReactNode }) {
    const [queryClient] = useState(() => createQueryClient());
    const [isRestored, setIsRestored] = useState(false);

    useEffect(() => {
        const initPersistence = async () => {
            const retry: AsyncPersistRetryer = async ({ persistedClient, error, errorCount }) => {
                if (errorCount < 3) return persistedClient;
                return undefined;
            };

            const asyncStoragePersister = createAsyncStoragePersister({
                storage: AsyncStorage,
                key: 'REACT_QUERY_CACHE',
                throttleTime: 1000,
                serialize: data => JSON.stringify(data),
                deserialize: str => JSON.parse(str),
                retry
            });

            try {
                persistQueryClient({
                    queryClient,
                    persister: asyncStoragePersister,
                    maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
                    buster: 'v1',
                    dehydrateOptions: {
                        shouldDehydrateQuery: query => {
                            const persistedQueries = ['events'];
                            return persistedQueries.some(key =>
                                Array.isArray(query.queryKey) &&
                                query.queryKey.includes(key)
                            );
                        },
                    },
                });
                setIsRestored(true);
            } catch (error) {
                console.error('Failed to restore query cache:', error);
                setIsRestored(true);
            }
        };

        initPersistence();

        return () => {
            queryClient.clear();
        };
    }, [queryClient]);

    if (!isRestored) {
        return null;
    }

    return (
        <QueryClientProvider client={queryClient}>
            {children}
        </QueryClientProvider>
    );
}