import { redirect } from "next/navigation";

import { auth } from "@/auth";
import { prisma } from "@/lib/db";
import { Role } from "@/lib/generated/prisma/enums";
import { getSignupMode } from "@/lib/settings";
import { getAiSettingsView } from "@/lib/ai-settings";
import { AdminUserTable, type AdminUserRow } from "@/components/admin/admin-user-table";
import { SignupModeSettings } from "@/components/admin/signup-mode-settings";
import { AiSettingsCard } from "@/components/admin/ai-settings-card";

export default async function AdminPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (session.user.role !== Role.ADMIN) redirect("/");

  const [users, signupMode, aiSettings] = await Promise.all([
    prisma.user.findMany({
      orderBy: { createdAt: "asc" },
      select: { id: true, name: true, email: true, role: true, createdAt: true },
    }),
    getSignupMode(),
    getAiSettingsView(),
  ]);

  const rows: AdminUserRow[] = users.map((user) => ({
    id: user.id,
    name: user.name,
    email: user.email,
    role: user.role,
    createdAtLabel: user.createdAt.toLocaleDateString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
    }),
  }));

  return (
    <div className="flex h-full flex-col gap-4 p-4">
      <div>
        <h1 className="text-2xl font-bold">Admin</h1>
        <p className="text-sm text-muted-foreground">
          Everyone with an account on this site. Click a role to change it.
        </p>
      </div>

      <AdminUserTable initialUsers={rows} currentUserId={session.user.id} />

      <SignupModeSettings initialMode={signupMode} />

      <AiSettingsCard initial={aiSettings} />
    </div>
  );
}
