import { auth } from '@/auth';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { notFound, redirect } from 'next/navigation';
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 { getEnquiryDetail, getEnquiryReferenceData } from '@/features/crm/enquiries/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';

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

export default async function LeadDetailRoute({ 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.crmLeadRead)));
  const canUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmLeadUpdate)));
  const canAssign =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmLeadAssign)));
  const queryClient = getQueryClient();

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

  const enquiry = canRead
    ? await getEnquiryDetail(id, session.user.activeOrganizationId, {
        organizationId: session.user.activeOrganizationId,
        userId: session.user.id,
        membershipRole: session.user.activeMembershipRole ?? 'user',
        businessRole: session.user.activeBusinessRole ?? 'sales_support'
      })
    : null;

  if (enquiry && enquiry.pipelineStage !== 'lead') {
    redirect(`/dashboard/crm/enquiries/${id}`);
  }

  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;

  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 lead.
        </div>
      }
    >
      {referenceData ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <EnquiryDetail
            enquiryId={id}
            referenceData={referenceData}
            relatedQuotations={[]}
            workspace='lead'
            canUpdate={canUpdate}
            canAssign={canAssign}
            canReassign={false}
            canViewRelatedQuotations={false}
            canManageFollowups={{
              create: false,
              update: false,
              delete: false
            }}
          />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
