import { Suspense } from "react";
import {
    dehydrate,
    HydrationBoundary,
    QueryClient,
} from "@tanstack/react-query";
import { Center, Loader } from "@mantine/core";
import PageBody from "@/app/deals/components/shared/PageBody/PageBody";
import { BoardsContextProvider } from "@/app/deals/contexts/BoardsContext";
import { ProjectsContextProvider } from "@/app/deals/contexts/ProjectsContext";
import { StatusesContextProvider } from "@/app/deals/contexts/StatusesContext";
import PageContainer from "@/components/layout/PageContainer/PageContainer";
import {
    getBoardsOptions,
    getProjectsOptions,
} from "@/lib/client/@tanstack/react-query.gen";
import { combineProviders } from "@/utils/combineProviders";

async function prefetchData() {
    const queryClient = new QueryClient();
    const projectsData = await queryClient.fetchQuery(getProjectsOptions());

    const firstProjectId = projectsData.items?.[0]?.id;
    if (!firstProjectId) return queryClient;

    await queryClient.prefetchQuery(
        getBoardsOptions({ path: { projectId: firstProjectId } })
    );

    return queryClient;
}

export default async function DealsPage() {
    const queryClient = await prefetchData();

    const Providers = combineProviders(
        [HydrationBoundary, { state: dehydrate(queryClient) }],
        [ProjectsContextProvider],
        [BoardsContextProvider],
        [StatusesContextProvider]
    );

    return (
        <Providers>
            <Suspense
                fallback={
                    <Center h="50vh">
                        <Loader size="lg" />
                    </Center>
                }>
                <PageContainer>
                    <PageBody />
                </PageContainer>
            </Suspense>
        </Providers>
    );
}
