import { auth } from "@/auth";
import PageContainer from "@/components/layout/page-container";
import { LeadFormTrigger } from "@/features/crm/leads/components/lead-form";
import { LeadList } from "@/features/crm/leads/components/lead-list";
import { getLeadReferenceData } from "@/features/crm/leads/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 Leads",
};

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

export default async function LeadsRoute(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.crmLeadRead)));

  const canCreate =
    session?.user?.systemRole === "super_admin" ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === "admin" ||
        session.user.activePermissions.includes(PERMISSIONS.crmLeadCreate)));

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

  const canDelete =
    session?.user?.systemRole === "super_admin" ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === "admin" ||
        session.user.activePermissions.includes(PERMISSIONS.crmLeadDelete)));

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

  if (!canRead || !session?.user?.activeOrganizationId) {
    return (
      <PageContainer access={false} pageTitle="CRM Leads">
        {null}
      </PageContainer>
    );
  }
  searchParamsCache.parse(searchParams);
  const referenceData = await getLeadReferenceData(
    session.user.activeOrganizationId,
  );

  return (
    <PageContainer
      pageTitle="CRM Leads"
      pageDescription="Marketing-qualified lead workspace before handoff into sales opportunities."
      pageHeaderAction={
        canCreate ? <LeadFormTrigger referenceData={referenceData} /> : null
      }
    >
      {referenceData ? (
        <LeadList
          referenceData={referenceData}
          canUpdate={canUpdate}
          canDelete={canDelete}
          canAssign={canAssign}
        />
      ) : null}
    </PageContainer>
  );
}

