import type { SearchParams } from "nuqs/server";
import Link from "next/link";
import PageContainer from "@/components/layout/page-container";
import { Icons } from "@/components/icons";
import { Button } from "@/components/ui/button";
import OnlineLessonsListingPage from "@/features/online-lessons/components/online-lessons-listing";
import { hasAnyPermission } from "@/lib/auth/authorization";
import { requireEmployeeDashboardAccess } from "@/lib/auth/page-guards";
import { searchParamsCache } from "@/lib/searchparams";

export const metadata = {
  title: "Dashboard : Online Lessons",
};

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

export default async function Page(props: PageProps) {
  const access = await requireEmployeeDashboardAccess();
  const searchParams = await props.searchParams;
  searchParamsCache.parse(searchParams);

  const permissions = access.session.user.effectivePermissions;
  const canCreateOnlineLessons = hasAnyPermission(permissions, ["online_lesson:create"]);
  const canManageOnlineLessons = hasAnyPermission(permissions, ["online_lesson:read_all"]);

  return (
    <PageContainer
      pageTitle="บทเรียนออนไลน์"
      pageDescription="เรียนรู้จากวิดีโอและเอกสารประกอบที่ HRD เผยแพร่ให้กับพนักงาน"
      pageHeaderAction={
        canCreateOnlineLessons ? (
          <Button asChild className="shrink-0 whitespace-nowrap">
            <Link href="/dashboard/online-lessons/manage/new">
              <Icons.add className="h-4 w-4" />
              เพิ่มบทเรียนออนไลน์
            </Link>
          </Button>
        ) : null
      }
    >
      <OnlineLessonsListingPage
        currentUserId={access.session.user.id}
        permissions={permissions}
        canManageOnlineLessons={canManageOnlineLessons}
      />
    </PageContainer>
  );
}
