import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import type { SearchParams } from 'nuqs/server';
import PageContainer from '@/components/layout/page-container';
import { crmReferenceQueryOptions, quotationsQueryOptions } from '@/features/crm-demo/api/queries';
import { QuotationsTablePage } from '@/features/crm-demo/components/quotations-table';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';

export const metadata = {
  title: 'Dashboard: CRM Quotations'
};

export default async function QuotationsRoute({
  searchParams
}: {
  searchParams: Promise<SearchParams>;
}) {
  searchParamsCache.parse(await searchParams);
  const page = searchParamsCache.get('page');
  const perPage = searchParamsCache.get('perPage');
  const search = searchParamsCache.get('name');
  const status = searchParamsCache.get('status');
  const quotationType = searchParamsCache.get('quotationType');
  const salesman = searchParamsCache.get('salesman');
  const hot = searchParamsCache.get('hot');
  const dateFrom = searchParamsCache.get('dateFrom');
  const dateTo = searchParamsCache.get('dateTo');
  const sort = searchParamsCache.get('sort');
  const queryClient = getQueryClient();

  void queryClient.prefetchQuery(crmReferenceQueryOptions());
  void queryClient.prefetchQuery(
    quotationsQueryOptions({
      page,
      limit: perPage,
      ...(search && { search }),
      ...(status && { status }),
      ...(quotationType && { quotationType }),
      ...(salesman && { salesman }),
      ...(hot && { hot }),
      ...(dateFrom && { dateFrom }),
      ...(dateTo && { dateTo }),
      ...(sort && { sort })
    })
  );

  return (
    <PageContainer
      pageTitle='Quotations'
      pageDescription='Quotation table with filters, hot project indicator, and kanban toggle'
    >
      <HydrationBoundary state={dehydrate(queryClient)}>
        <QuotationsTablePage />
      </HydrationBoundary>
    </PageContainer>
  );
}
