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

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

export default async function CustomersRoute({
  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('customerStatus');
  const branch = searchParamsCache.get('branch');
  const sort = searchParamsCache.get('sort');
  const queryClient = getQueryClient();

  void queryClient.prefetchQuery(crmReferenceQueryOptions());
  void queryClient.prefetchQuery(
    customersQueryOptions({
      page,
      limit: perPage,
      ...(search && { search }),
      ...(status && { status }),
      ...(branch && { branch }),
      ...(sort && { sort })
    })
  );

  return (
    <PageContainer
      pageTitle='Customers'
      pageDescription='Customer master พร้อม status, branch, contacts และ drawer สำหรับ create/edit'
    >
      <HydrationBoundary state={dehydrate(queryClient)}>
        <CustomersTablePage />
      </HydrationBoundary>
    </PageContainer>
  );
}
