'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { loggerLink, httpBatchLink, createTRPCClient } from '@trpc/client';
import { TRPCProvider } from '@fenghuo/client';
import { useMemo, useState } from 'react';
import superjson from 'superjson';
import type { AppRouter } from '@fenghuo/api/trpc';
import { useToken } from '@/components/providers/token-provider';

interface QueryProviderProps {
	children: React.ReactNode;
}

export default function QueryProvider({ children }: QueryProviderProps) {
	// 使用token hook，自动响应token变化
	const { accessToken } = useToken();

	const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';

	const [queryClient] = useState(
		() =>
			new QueryClient({
				defaultOptions: {
					queries: {
						staleTime: 1000 * 60 * 5,
						retry: 3,
						retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
						refetchOnWindowFocus: false,
					},
				},
			}),
	);

	const trpcClient = useMemo(() => {
		const headers = async () => ({
			...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
		});

		const links = [
			httpBatchLink({
				url: `${apiUrl}/trpc`,
				headers,
				transformer: superjson,
			}),
			loggerLink({
				enabled: (opts) =>
					process.env.NODE_ENV === 'development' || (opts.direction === 'down' && opts.result instanceof Error),
			}),
		];

		return createTRPCClient<AppRouter>({
			links,
		});
	}, [accessToken, apiUrl]);

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