import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import type { LeadReferenceData } from '../api/types';
import { leadsQueryOptions } from '../api/queries';
import { LeadsTable } from './leads-table';

export function LeadList({
  referenceData,
  canUpdate,
  canDelete,
  canAssign
}: {
  referenceData: LeadReferenceData;
  canUpdate: boolean;
  canDelete: boolean;
  canAssign: boolean;
}) {
  const page = searchParamsCache.get('page');
  const limit = searchParamsCache.get('perPage');
  const search = searchParamsCache.get('name');
  const status = searchParamsCache.get('status');
  const branch = searchParamsCache.get('branch');
  const customer = searchParamsCache.get('customer');
  const sort = searchParamsCache.get('sort');
  const filters = {
    page,
    limit,
    ...(search && { search }),
    ...(status && { status }),
    ...(branch && { branchId: branch }),
    ...(customer && { customerId: customer }),
    ...(sort && { sort })
  };
  const queryClient = getQueryClient();
  void queryClient.prefetchQuery(leadsQueryOptions(filters));

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