import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { auth } from '@/auth';
import PageContainer from '@/components/layout/page-container';
import { crmDashboardQueryOptions } from '@/features/crm/dashboard/api/queries';
import { CrmDashboard } from '@/features/crm/dashboard/components/crm-dashboard';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import type { SearchParams } from 'nuqs/server';

export const metadata = {
  title: 'Dashboard: CRM'
};

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

export default async function CrmDashboardRoute(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.crmDashboardRead)));
  const canExport =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmDashboardExport)));

  searchParamsCache.parse(searchParams);

  const filters = {
    dateFrom: searchParamsCache.get('dateFrom'),
    dateTo: searchParamsCache.get('dateTo'),
    branch: searchParamsCache.get('branch'),
    salesman: searchParamsCache.get('salesman'),
    projectPartyRole: searchParamsCache.get('projectPartyRole'),
    productType: searchParamsCache.get('productType')
  };
  const queryClient = getQueryClient();

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

  return (
    <PageContainer
      pageTitle='CRM Dashboard'
      pageDescription='Dashboard กลางสำหรับติดตาม KPI, มูลค่าใบเสนอราคา, งานอนุมัติเอกสาร, และภาพรวมการขายจากข้อมูล CRM จริง'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to the CRM dashboard.
        </div>
      }
    >
      {canRead ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <CrmDashboard canExport={canExport} />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
