import { auth } from '@/auth';
import PageContainer from '@/components/layout/page-container';
import QuotationListing from '@/features/crm/quotations/components/quotation-listing';
import { QuotationFormSheetTrigger } from '@/features/crm/quotations/components/quotation-form-sheet';
import { getQuotationReferenceData } from '@/features/crm/quotations/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { searchParamsCache } from '@/lib/searchparams';
import type { SearchParams } from 'nuqs/server';

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

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

export default async function QuotationsRoute(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.crmQuotationRead)));
  const canCreate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationCreate)));
  const canUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationUpdate)));
  const canDelete =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationDelete)));

  searchParamsCache.parse(searchParams);

  const referenceData =
    canRead && session?.user?.activeOrganizationId
      ? await getQuotationReferenceData(session.user.activeOrganizationId)
      : null;

  return (
    <PageContainer
      pageTitle='ใบเสนอราคา'
      pageDescription='ทะเบียนใบเสนอราคา พร้อม revision, ผู้เกี่ยวข้องในโครงการ, และรายการคำนวณจากระบบ'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to CRM quotations.
        </div>
      }
      pageHeaderAction={
        canCreate && referenceData ? <QuotationFormSheetTrigger referenceData={referenceData} /> : null
      }
    >
      {referenceData ? (
        <QuotationListing referenceData={referenceData} canUpdate={canUpdate} canDelete={canDelete} />
      ) : null}
    </PageContainer>
  );
}
