import { auth } from '@/auth';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import PageContainer from '@/components/layout/page-container';
import { quotationDocumentPreviewOptions } from '@/features/crm/quotations/document/queries';
import {
  quotationAttachmentsOptions,
  quotationByIdOptions,
  quotationCustomersOptions,
  quotationFollowupsOptions,
  quotationItemsOptions,
  quotationRevisionsOptions,
  quotationTopicsOptions
} from '@/features/crm/quotations/api/queries';
import { QuotationDetail } from '@/features/crm/quotations/components/quotation-detail';
import { getQuotationReferenceData } from '@/features/crm/quotations/server/service';
import { approvalsQueryOptions } from '@/features/foundation/approval/queries';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';

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

export default async function QuotationDetailRoute({ 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.crmQuotationRead)));
  const canUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationUpdate)));
  const canManageItems =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationItemManage)));
  const canManageCustomers =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationCustomerManage)));
  const canManageTopics =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationTopicManage)));
  const canManageFollowups =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationFollowupManage)));
  const canManageAttachments =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationAttachmentManage)));
  const canCreateRevision =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationRevisionCreate)));
  const canSubmitApproval =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmApprovalSubmit)));
  const canApproveApproval =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmApprovalApprove)));
  const canRejectApproval =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmApprovalReject)));
  const canReturnApproval =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmApprovalReturn)));
  const isOrgAdmin =
    session?.user?.systemRole === 'super_admin' || session?.user?.activeMembershipRole === 'admin';
  const canPreviewDocument =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationDocumentPreview)));
  const canPreviewPdf =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationPdfPreview)));
  const canPreviewCustomerPackage = canPreviewPdf;
  const canDownloadPdf =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationPdfDownload)));
  const canGenerateCustomerPackage = canDownloadPdf;
  const canDownloadCustomerPackage = canDownloadPdf;
  const canGenerateApprovedPdf =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationPdfGenerateApproved)));
  const queryClient = getQueryClient();

  if (canRead) {
    void queryClient.prefetchQuery(quotationByIdOptions(id));
    void queryClient.prefetchQuery(quotationItemsOptions(id));
    void queryClient.prefetchQuery(quotationCustomersOptions(id));
    void queryClient.prefetchQuery(quotationTopicsOptions(id));
    void queryClient.prefetchQuery(quotationFollowupsOptions(id));
    void queryClient.prefetchQuery(quotationAttachmentsOptions(id));
    void queryClient.prefetchQuery(quotationRevisionsOptions(id));
    void queryClient.prefetchQuery(
      approvalsQueryOptions({
        entityType: 'quotation',
        entityId: id,
        limit: 20
      })
    );
    if (canPreviewDocument) {
      void queryClient.prefetchQuery(quotationDocumentPreviewOptions(id));
    }
  }

  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 this quotation.
        </div>
      }
    >
      {referenceData ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <QuotationDetail
            quotationId={id}
            referenceData={referenceData}
            canUpdate={canUpdate}
            canManageItems={canManageItems}
            canManageCustomers={canManageCustomers}
            canManageTopics={canManageTopics}
            canManageFollowups={canManageFollowups}
            canManageAttachments={canManageAttachments}
            canCreateRevision={canCreateRevision}
            canSubmitApproval={canSubmitApproval}
            canApproveApproval={canApproveApproval}
            canRejectApproval={canRejectApproval}
            canReturnApproval={canReturnApproval}
            activeBusinessRole={session?.user?.activeBusinessRole ?? null}
            isOrgAdmin={isOrgAdmin}
            currentUserId={session?.user?.id ?? ''}
            canPreviewDocument={canPreviewDocument}
            canPreviewPdf={canPreviewPdf}
            canPreviewCustomerPackage={canPreviewCustomerPackage}
            canDownloadPdf={canDownloadPdf}
            canGenerateCustomerPackage={canGenerateCustomerPackage}
            canDownloadCustomerPackage={canDownloadCustomerPackage}
            canGenerateApprovedPdf={canGenerateApprovedPdf}
          />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
