import { auth } from '@/auth';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { notFound } from 'next/navigation';
import PageContainer from '@/components/layout/page-container';
import {
  opportunityByIdOptions,
  opportunityFollowupsOptions,
  opportunityProjectPartiesOptions
} from '@/features/crm/opportunities/api/queries';
import { OpportunityDetail } from '@/features/crm/opportunities/components/opportunity-detail';
import { getOpportunityDetail, getOpportunityReferenceData } from '@/features/crm/opportunities/server/service';
import { getLeadById } from '@/features/crm/leads/server/service';
import { listOpportunityQuotationRelations } from '@/features/crm/quotations/server/service';
import { getQuotationReferenceData } 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 OpportunityDetailRoute({ 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.crmOpportunityRead)));

  const canUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmOpportunityUpdate)));

  const canAssign =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmOpportunityAssign)));

  const canReassign =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmOpportunityReassign)));

  const canManageFollowups = {
    create:
      session?.user?.systemRole === 'super_admin' ||
      (!!session?.user?.activeOrganizationId &&
        (session.user.activeMembershipRole === 'admin' ||
          session.user.activePermissions.includes(PERMISSIONS.crmOpportunityFollowupCreate))),
    update:
      session?.user?.systemRole === 'super_admin' ||
      (!!session?.user?.activeOrganizationId &&
        (session.user.activeMembershipRole === 'admin' ||
          session.user.activePermissions.includes(PERMISSIONS.crmOpportunityFollowupUpdate))),
    delete:
      session?.user?.systemRole === 'super_admin' ||
      (!!session?.user?.activeOrganizationId &&
        (session.user.activeMembershipRole === 'admin' ||
          session.user.activePermissions.includes(PERMISSIONS.crmOpportunityFollowupDelete)))
  };

  const canMarkWon =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmOpportunityMarkWon)));

  const canMarkLost =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmOpportunityMarkLost)));

  const canReopen =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmOpportunityReopen)));

  const canViewRelatedQuotations =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationRead)));

  const canCreateQuotation =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmQuotationCreate)));

  const canViewOutcomeCommercialData = canRead;

  if (!canRead || !session?.user?.activeOrganizationId || !session.user.id) {
    notFound();
  }

  const accessContext = {
    organizationId: session.user.activeOrganizationId,
    userId: session.user.id,
    membershipRole: session.user.activeMembershipRole ?? 'user',
    businessRole: session.user.activeBusinessRole ?? 'sales_support',
    businessRoles: [session.user.activeBusinessRole ?? 'sales_support'],
    permissions: session.user.activePermissions ?? [],
    branchScopeIds: session.user.activeBranchScopeIds ?? [],
    productTypeScopeIds: session.user.activeProductTypeScopeIds ?? [],
    ownershipScope: session.user.activeOwnershipScope ?? 'organization',
    branchScopeMode: 'all',
    productScopeMode: 'all',
    approvalAuthority: null
  } as const;

  const queryClient = getQueryClient();
  await Promise.all([
    queryClient.prefetchQuery(opportunityByIdOptions(id)),
    queryClient.prefetchQuery(opportunityFollowupsOptions(id)),
    queryClient.prefetchQuery(opportunityProjectPartiesOptions(id))
  ]);

  const opportunityDetail = await getOpportunityDetail(id, session.user.activeOrganizationId, accessContext);
  const [referenceData, relatedQuotations, sourceLead, quotationReferenceData] = await Promise.all([
    getOpportunityReferenceData(session.user.activeOrganizationId),
    listOpportunityQuotationRelations(id, session.user.activeOrganizationId),
    opportunityDetail.leadId
      ? getLeadById(opportunityDetail.leadId, session.user.activeOrganizationId).catch(() => null)
      : Promise.resolve(null),
    canCreateQuotation ? getQuotationReferenceData(session.user.activeOrganizationId) : Promise.resolve(null)
  ]);

  return (
    <PageContainer
      pageTitle='Opportunity Detail'
      pageDescription='Sales execution workspace for follow-up continuity, quotation readiness, and outcome control.'
    >
      <HydrationBoundary state={dehydrate(queryClient)}>
        <OpportunityDetail
          opportunityId={id}
          referenceData={referenceData}
          relatedQuotations={relatedQuotations}
          workspace='opportunity'
          canUpdate={canUpdate}
          canAssign={canAssign}
          canReassign={canReassign}
          canViewRelatedQuotations={canViewRelatedQuotations}
          canViewOutcomeCommercialData={canViewOutcomeCommercialData}
          canMarkWon={canMarkWon}
          canMarkLost={canMarkLost}
          canReopen={canReopen}
          canCreateQuotation={canCreateQuotation}
          canManageFollowups={canManageFollowups}
          sourceLead={
            sourceLead
              ? {
                  id: sourceLead.id,
                  code: sourceLead.code,
                  projectName: sourceLead.projectName,
                  status: sourceLead.statusLabel,
                  awareness: sourceLead.awarenessLabel
                }
              : null
          }
          quotationReferenceData={quotationReferenceData}
        />
      </HydrationBoundary>
    </PageContainer>
  );
}

