import { auth } from '@/auth';
import PageContainer from '@/components/layout/page-container';
import CustomerListing from '@/features/crm/customers/components/customer-listing';
import { CustomerFormSheetTrigger } from '@/features/crm/customers/components/customer-form-sheet';
import { getCustomerReferenceData } from '@/features/crm/customers/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 Customers'
};

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

export default async function CustomersRoute(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.crmCustomerRead)));
  const canCreate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmCustomerCreate)));
  const canUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmCustomerUpdate)));
  const canDelete =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmCustomerDelete)));

  searchParamsCache.parse(searchParams);

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

  return (
    <PageContainer
      pageTitle='ลูกค้า'
      pageDescription='ทะเบียนลูกค้า พร้อมข้อมูลผู้ติดต่อ สาขาที่ดูแล และประวัติการใช้งานใน CRM'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to CRM customer records.
        </div>
      }
      pageHeaderAction={
        canCreate && referenceData ? (
          <CustomerFormSheetTrigger referenceData={referenceData} />
        ) : null
      }
    >
      {referenceData ? (
        <CustomerListing
          referenceData={referenceData}
          canUpdate={canUpdate}
          canDelete={canDelete}
        />
      ) : null}
    </PageContainer>
  );
}
