import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { auth } from '@/auth';
import PageContainer from '@/components/layout/page-container';
import {
  crmLeadAgingReportQueryOptions,
  crmReportFiltersQueryOptions
} from '@/features/crm/reports/api/queries';
import { AgingReportView } from '@/features/crm/reports/components/aging-report-view';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';
import type { SearchParams } from 'nuqs/server';

export const metadata = {
  title: 'CRM Lead Aging Report'
};

type PageProps = {
  searchParams: Promise<SearchParams>;
};

function getFilterValue(value: string | string[] | undefined): string | null {
  return typeof value === 'string' ? value : null;
}

export default async function CrmLeadAgingRoute(props: PageProps) {
  const searchParams = await props.searchParams;
  const session = await auth();
  const canRead =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmReportRead)));
  const canExport =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmReportExport)));
  const queryClient = getQueryClient();
  const filters = {
    dateFrom: getFilterValue(searchParams.dateFrom),
    dateTo: getFilterValue(searchParams.dateTo),
    branch: getFilterValue(searchParams.branch),
    productType: getFilterValue(searchParams.productType),
    sales: null,
    customerOwner: getFilterValue(searchParams.customerOwner),
    leadSource: getFilterValue(searchParams.leadSource)
  };

  if (canRead) {
    void queryClient.prefetchQuery(crmReportFiltersQueryOptions());
    void queryClient.prefetchQuery(crmLeadAgingReportQueryOptions(filters));
  }

  return (
    <PageContainer
      pageTitle='Lead Aging Report'
      pageDescription='Identify stagnant leads before they move deeper into the pipeline.'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to CRM lead aging reports.
        </div>
      }
    >
      {canRead ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <AgingReportView variant='lead' canExport={canExport} />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
