import * as React from "react";
import { redirect } from "next/navigation";
import { AppShell } from "@/components/layout/app-shell";
import { prisma } from "@/lib/db/prisma";
import {
  filterNavigationForUser,
  getPrimaryRoleLabel,
  hasAnyPermission,
  requirePageAuth,
} from "@/lib/auth/rbac";
import { isEmployeePortalOnlyUser } from "@/lib/validation/workplace";
import {
  canAccessHrWorkspace,
  filterHrNavigationForUser,
  isHrWorkspaceUser,
} from "@/lib/hr/workspace";
import { formatRelativeTimestamp } from "@/lib/utils";
import type { TopbarNotification } from "@/components/layout/topbar";

export const dynamic = "force-dynamic";

export default async function PlatformLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const auth = await requirePageAuth();
  if (isEmployeePortalOnlyUser(auth)) {
    redirect("/workplace");
  }

  const hrMode = isHrWorkspaceUser(auth);
  const navItems = hrMode ? filterHrNavigationForUser(auth) : filterNavigationForUser(auth);

  const now = new Date();
  const [notificationsRaw, taskBadgeCount] = await Promise.all([
    prisma.notification.findMany({
      where: { userId: auth.userId },
      include: { company: true },
      orderBy: { createdAt: "desc" },
      take: 8,
    }),
    auth.allowedCompanyIds.length > 0
      ? prisma.task.count({
          where: {
            companyId: { in: auth.allowedCompanyIds },
            status: { in: ["PENDING", "IN_PROGRESS", "WAITING_FOR_APPROVAL", "BLOCKED"] },
            ...(hrMode ? { assignedDepartmentRole: "HR" } : { dueDate: { lt: now } }),
          },
        })
      : Promise.resolve(0),
  ]);

  const notifications: TopbarNotification[] = notificationsRaw.map((n) => ({
    id: n.id,
    title: n.title,
    body: n.body,
    companyCode: n.company?.code ?? "SMC",
    linkUrl: n.linkUrl ?? (hrMode ? "/hr" : "/"),
    isRead: n.isRead,
    timeAgo: formatRelativeTimestamp(n.createdAt),
  }));

  return (
    <React.Suspense fallback={<div className="min-h-screen bg-[#F7F9FC]" />}>
      <AppShell
        navItems={navItems}
        workspaceMode={hrMode ? "hr" : "admin"}
        canAccessHrWorkspace={canAccessHrWorkspace(auth)}
        allowedCompanies={auth.allowedCompanies.map((c) => ({
          code: c.code,
          name: c.name,
        }))}
        canViewAllCompanies={auth.hasGroupWideAccess || auth.allowedCompanies.length > 1}
        user={{
          name: auth.name,
          email: auth.email,
          roleLabel: hrMode ? "People Operations" : getPrimaryRoleLabel(auth),
          canAccessSettings: hasAnyPermission(auth, ["user.manage", "role.manage", "company.manage"]),
        }}
        notifications={notifications}
        overdueTasksCount={taskBadgeCount}
      >
        {children}
      </AppShell>
    </React.Suspense>
  );
}
