import { redirect } from "next/navigation";
import { HeartPulse } from "lucide-react";

import { getCurrentAuthContext } from "@/modules/core/server/auth";
import { hasPermission } from "@/modules/core/server/permissions";
import { HealthAdminClient } from "@/modules/health/components/HealthAdminClient";
import { listHealthAdminData } from "@/modules/health/server/operations";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

export async function renderHealthWorkspacePage(): Promise<React.ReactElement> {
  const context = await getCurrentAuthContext();
  if (!context) {
    redirect("/login");
  }

  if (!hasPermission(context.permissions, "health:read")) {
    redirect(getWorkspaceHref(context.organization?.slug, "/dashboard"));
  }

  const organizationId = context.organization?.id;
  if (!organizationId) {
    redirect(getWorkspaceHref(context.organization?.slug, "/dashboard"));
  }

  const data = await listHealthAdminData(organizationId);

  return (
    <div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
      <section className="flex flex-col gap-3 border-b pb-4 lg:flex-row lg:items-start lg:justify-between">
        <div className="flex min-w-0 items-center gap-3">
          <span className="inline-flex size-9 items-center justify-center rounded-md bg-secondary text-primary">
            <HeartPulse className="size-4" aria-hidden="true" />
          </span>
          <div className="min-w-0">
            <h1 className="truncate text-xl font-semibold tracking-normal">健康照护</h1>
            <p className="mt-1 truncate text-sm text-muted-foreground">健康档案、生命体征、慢病管理与异常复核</p>
          </div>
        </div>
      </section>

      <HealthAdminClient canManage={hasPermission(context.permissions, "health:manage")} initialData={data} />
    </div>
  );
}
