import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import type { EnquiryReferenceData } from '../api/types';
import { enquiriesQueryOptions } from '../api/queries';
import { EnquiriesTable } from './enquiries-table';

export default function EnquiryListing({
  referenceData,
  workspace,
  canUpdate,
  canDelete,
  canAssign,
  canReassign
}: {
  referenceData: EnquiryReferenceData;
  workspace: 'lead' | 'enquiry';
  canUpdate: boolean;
  canDelete: boolean;
  canAssign: boolean;
  canReassign: boolean;
}) {
  const page = searchParamsCache.get('page');
  const limit = searchParamsCache.get('perPage');
  const search = searchParamsCache.get('name');
  const status = searchParamsCache.get('status');
  const productType = searchParamsCache.get('productType');
  const priority = searchParamsCache.get('priority');
  const branch = searchParamsCache.get('branch');
  const customer = searchParamsCache.get('customer');
  const sort = searchParamsCache.get('sort');
  const filters = {
    page,
    limit,
    pipelineStage: workspace,
    ...(search && { search }),
    ...(status && { status }),
    ...(productType && { productType }),
    ...(priority && { priority }),
    ...(branch && { branch }),
    ...(customer && { customer }),
    ...(sort && { sort })
  };
  const queryClient = getQueryClient();

  void queryClient.prefetchQuery(enquiriesQueryOptions(filters));

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