import {
    dehydrate,
    HydrationBoundary,
    QueryClient,
} from "@tanstack/react-query";
import { Suspense } from "react";
import { Loader, Center } from "@mantine/core";
import dynamic from "next/dynamic";
import {
    getBoardsOptions,
    getProjectsOptions,
} from "@/lib/client/@tanstack/react-query.gen";
import { combineProviders } from "@/utils/combineProviders";

// Dynamic imports for better code splitting
const PageBody = dynamic(() => import("@/app/deals/components/shared/PageBody/PageBody"), {
    loading: () => <Center h={400}><Loader /></Center>
});
const BoardsContextProvider = dynamic(() => import("@/app/deals/contexts/BoardsContext").then(mod => ({ default: mod.BoardsContextProvider })));
const ProjectsContextProvider = dynamic(() => import("@/app/deals/contexts/ProjectsContext").then(mod => ({ default: mod.ProjectsContextProvider })));
const StatusesContextProvider = dynamic(() => import("@/app/deals/contexts/StatusesContext").then(mod => ({ default: mod.StatusesContextProvider })));
const ViewContextProvider = dynamic(() => import("@/app/deals/contexts/ViewContext").then(mod => ({ default: mod.ViewContextProvider })));
const PageBlock = dynamic(() => import("@/components/layout/PageBlock/PageBlock"));
const PageContainer = dynamic(() => import("@/components/layout/PageContainer/PageContainer"));
const TopToolPanel = dynamic(() => import("./components/desktop/TopToolPanel/TopToolPanel"), {
    loading: () => <div style={{ height: 60 }} />
});

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],
        [ViewContextProvider]
    );

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