import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import type { CustomerReferenceData } from '../api/types';
import { customersQueryOptions } from '../api/queries';
import { CustomersTable } from './customers-table';

export default function CustomerListing({
  referenceData,
  canUpdate,
  canDelete
}: {
  referenceData: CustomerReferenceData;
  canUpdate: boolean;
  canDelete: boolean;
}) {
  const page = searchParamsCache.get('page');
  const limit = searchParamsCache.get('perPage');
  const search = searchParamsCache.get('name');
  const customerStatus = searchParamsCache.get('customerStatus');
  const customerType = searchParamsCache.get('customerType');
  const branch = searchParamsCache.get('branch');
  const sort = searchParamsCache.get('sort');
  const filters = {
    page,
    limit,
    ...(search && { search }),
    ...(customerStatus && { customerStatus }),
    ...(customerType && { customerType }),
    ...(branch && { branch }),
    ...(sort && { sort })
  };
  const queryClient = getQueryClient();

  void queryClient.prefetchQuery(customersQueryOptions(filters));

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <CustomersTable referenceData={referenceData} canUpdate={canUpdate} canDelete={canDelete} />
    </HydrationBoundary>
  );
}
