"use client";

import { useState, type ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { trpc } from "@/lib/trpc";
import { httpBatchLink } from "@trpc/client";

export function TrpcContextProvider({ children }: { children: ReactNode }) {
  const [queryClient] = useState(() => new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 60_000, // 30 seconds
      },
    },
  }))
  const [trpcQueryClient] = useState(() => trpc.createClient({
    links: [
      httpBatchLink({
        url: "/api",
      }),
    ],
  }));
  return (
    <trpc.Provider client={trpcQueryClient} queryClient={queryClient}>
      <QueryClientProvider client={queryClient}>
        {children}
        <ReactQueryDevtools />
      </QueryClientProvider>
    </trpc.Provider>
  );
}
