import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import type { SearchParams } from 'nuqs/server';
import { auth } from '@/auth';
import PageContainer from '@/components/layout/page-container';
import { crmDashboardQueryOptions } from '@/features/crm/dashboard/api/queries';
import {
  createEmptyCrmDashboardResponse,
  type CrmDashboardFilters
} from '@/features/crm/dashboard/api/types';
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';

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

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

function normalizeRequiredFilters(filters: CrmDashboardFilters): Required<CrmDashboardFilters> {
  return {
    dateFrom: filters.dateFrom ?? null,
    dateTo: filters.dateTo ?? null,
    branch: filters.branch ?? null,
    salesman: filters.salesman ?? null,
    projectPartyRole: filters.projectPartyRole ?? null,
    productType: filters.productType ?? null
  };
}

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();
  const dashboardQuery = crmDashboardQueryOptions(filters);

  if (canRead) {
    try {
      await queryClient.prefetchQuery(dashboardQuery);
    } catch (error) {
      console.error('CRM dashboard prefetch failed', error);
      queryClient.setQueryData(
        dashboardQuery.queryKey,
        createEmptyCrmDashboardResponse(
          normalizeRequiredFilters(filters),
          'CRM dashboard data could not be loaded.'
        )
      );
    }
  }

  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>
  );
}
