import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpBatchLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import { useState, type ReactNode } from "react";
import SuperJSON from "superjson";

import { useAuthClient } from "@/contexts/AuthContext";
import type { AppRouter } from "beenvoice/server/api/root";

export const api = createTRPCReact<AppRouter>();

function createQueryClient() {
  return new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 30_000,
        retry: 1,
      },
    },
  });
}

export function TRPCProvider({ apiUrl, children }: { apiUrl: string; children: ReactNode }) {
  const authClient = useAuthClient();
  const [queryClient] = useState(createQueryClient);
  const [trpcClient] = useState(() =>
    api.createClient({
      links: [
        httpBatchLink({
          url: `${apiUrl}/api/trpc`,
          transformer: SuperJSON,
          headers() {
            const cookie = (
              authClient as { getCookie?: () => string | null | undefined }
            ).getCookie?.();
            return cookie ? { cookie } : {};
          },
        }),
      ],
    }),
  );

  return (
    <api.Provider client={trpcClient} queryClient={queryClient}>
      <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
    </api.Provider>
  );
}
