"use client";
import { useState, ReactNode } from "react";
import superjson from "superjson";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { makeQueryClient } from "@/lib/tanstack-query/query-client";
import { createTRPCClient, httpBatchLink, isNonJsonSerializable, httpLink, splitLink } from "@trpc/client";
import { AppRouter } from "@/lib/trpc/router";
import { api, TRPCProvider } from "@/lib/trpc/client";

let clientQueryClientSingleton: QueryClient | undefined;

const getQueryClient = () => {
    if(typeof window === "undefined") {
        return makeQueryClient();
    }

    if(!clientQueryClientSingleton) {
        clientQueryClientSingleton = makeQueryClient();
    }

    return clientQueryClientSingleton;
}

function getBaseUrl(): string {
    if (typeof window !== 'undefined')
        return '';

    if (process.env.VERCEL_URL)
        return `https://${process.env.VERCEL_URL}`;

    if (process.env.NEXT_PUBLIC_APP_URL)
        return process.env.NEXT_PUBLIC_APP_URL;

    return `http://localhost:${process.env.PORT ?? 3000}`;
}

export function TRPCReactProvider(
    props: Readonly<{
        children: ReactNode;
    }>,
) {
    const queryClient = getQueryClient();
    const [trpcClient] = useState(() =>
        createTRPCClient<AppRouter>({
            links: [
                splitLink({
                    condition: (op) => isNonJsonSerializable(op.input),
                    true: httpLink({
                        transformer: superjson,
                        url: `${getBaseUrl()}/api/trpc`
                    }),
                    false: httpBatchLink({
                        transformer: superjson,
                        url: `${getBaseUrl()}/api/trpc`
                    }),
                })
            ]
        })
    );

    const [trpcReactClient] = useState(() => api.createClient({
        links: [
            splitLink({
                condition: (op) => isNonJsonSerializable(op.input),
                true: httpLink({
                    transformer: superjson,
                    url: `${getBaseUrl()}/api/trpc`
                }),
                false: httpBatchLink({
                    transformer: superjson,
                    url: `${getBaseUrl()}/api/trpc`
                })
            })
        ]
    }));

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