import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import type { QuotationReferenceData } from '../api/types';
import { quotationsQueryOptions } from '../api/queries';
import { QuotationsTable } from './quotations-table';

export default function QuotationListing({
  referenceData,
  canUpdate,
  canDelete
}: {
  referenceData: QuotationReferenceData;
  canUpdate: boolean;
  canDelete: boolean;
}) {
  const page = searchParamsCache.get('page');
  const limit = searchParamsCache.get('perPage');
  const search = searchParamsCache.get('name');
  const status = searchParamsCache.get('status');
  const quotationType = searchParamsCache.get('quotationType');
  const branch = searchParamsCache.get('branch');
  const customer = searchParamsCache.get('customer');
  const enquiry = searchParamsCache.get('enquiry');
  const hot = searchParamsCache.get('hot');
  const sort = searchParamsCache.get('sort');
  const filters = {
    page,
    limit,
    ...(search && { search }),
    ...(status && { status }),
    ...(quotationType && { quotationType }),
    ...(branch && { branch }),
    ...(customer && { customer }),
    ...(enquiry && { enquiry }),
    ...(hot && { hot }),
    ...(sort && { sort })
  };
  const queryClient = getQueryClient();

  void queryClient.prefetchQuery(quotationsQueryOptions(filters));

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