import { auth } from '@/auth';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import PageContainer from '@/components/layout/page-container';
import {
  enquiryByIdOptions,
  enquiryFollowupsOptions,
  enquiryProjectPartiesOptions
} from '@/features/crm/enquiries/api/queries';
import { EnquiryDetail } from '@/features/crm/enquiries/components/enquiry-detail';
import { getEnquiryReferenceData } from '@/features/crm/enquiries/server/service';
import { listEnquiryQuotationRelations } from '@/features/crm/quotations/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';

type PageProps = {
  params: Promise<{ id: string }>;
};

export default async function EnquiryDetailRoute({ params }: PageProps) {
  const { id } = await params;
  const session = await auth();
  const canRead =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmEnquiryRead)));
  const canUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmEnquiryUpdate)));
  const canFollowupCreate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmEnquiryFollowupCreate)));
  const canFollowupUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmEnquiryFollowupUpdate)));
  const canFollowupDelete =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmEnquiryFollowupDelete)));
  const canAssign =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmEnquiryAssign)));
  const canReassign =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmEnquiryReassign)));
  const canReadQuotation =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationRead)));
  const queryClient = getQueryClient();

  if (canRead) {
    void queryClient.prefetchQuery(enquiryByIdOptions(id));
    void queryClient.prefetchQuery(enquiryProjectPartiesOptions(id));
    void queryClient.prefetchQuery(enquiryFollowupsOptions(id));
  }

  const referenceData =
    canRead && session?.user?.activeOrganizationId
      ? await getEnquiryReferenceData(session.user.activeOrganizationId)
      : null;
  const relatedQuotations =
    canRead && canReadQuotation && session?.user?.activeOrganizationId
      ? await listEnquiryQuotationRelations(id, session.user.activeOrganizationId)
      : [];

  return (
    <PageContainer
      pageTitle='รายละเอียดโอกาสขาย'
      pageDescription='ข้อมูลโอกาสขาย ไทม์ไลน์การติดตาม และสถานะการดูแลของฝ่ายขาย'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to this enquiry.
        </div>
      }
    >
      {referenceData ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <EnquiryDetail
            enquiryId={id}
            referenceData={referenceData}
            relatedQuotations={relatedQuotations}
            workspace='enquiry'
            canUpdate={canUpdate}
            canAssign={canAssign}
            canReassign={canReassign}
            canViewRelatedQuotations={canReadQuotation}
            canManageFollowups={{
              create: canFollowupCreate,
              update: canFollowupUpdate,
              delete: canFollowupDelete
            }}
          />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
