import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { auth } from '@/auth';
import PageContainer from '@/components/layout/page-container';
import {
  crmOpportunityAgingReportQueryOptions,
  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 Opportunity 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 CrmOpportunityAgingRoute(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: getFilterValue(searchParams.sales),
    customerOwner: null,
    leadSource: null
  };

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

  return (
    <PageContainer
      pageTitle='Opportunity Aging Report'
      pageDescription='Identify stalled opportunities that need follow-up or progression.'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to CRM opportunity aging reports.
        </div>
      }
    >
      {canRead ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <AgingReportView variant='opportunity' canExport={canExport} />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}

