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

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

export default async function EnquiriesRoute({
  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 productType = searchParamsCache.get('productType');
  const salesman = searchParamsCache.get('salesman');
  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(
    enquiriesQueryOptions({
      page,
      limit: perPage,
      ...(search && { search }),
      ...(status && { status }),
      ...(productType && { productType }),
      ...(salesman && { salesman }),
      ...(dateFrom && { dateFrom }),
      ...(dateTo && { dateTo }),
      ...(sort && { sort })
    })
  );

  return (
    <PageContainer
      pageTitle='Enquiries'
      pageDescription='List ของ sales opportunity พร้อม filter, date range และ convert to quotation'
    >
      <HydrationBoundary state={dehydrate(queryClient)}>
        <EnquiriesTablePage />
      </HydrationBoundary>
    </PageContainer>
  );
}
