import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import AdminDashboard from "@/components/admin/admin-dashboard";
import Footer from "@/components/footer";
import Navbar from "@/components/navbar";
import { authOptions } from "@/lib/auth";
import { db } from "@/lib/db";

export const dynamic = "force-dynamic";

type AdminWithUser = {
  id: string;
  discordId: string;
  user: {
    name?: string | null;
    email?: string | null;
    discordUsername?: string | null;
  } | null;
};

type GradeRecord = {
  id: string;
  name: string;
  price: number;
  description: string;
};

type EventRecord = {
  id: string;
  title: string;
  description: string;
  eventDate: Date;
};

export default async function AdminPage() {
  const session = await getServerSession(authOptions);
  const discordId = session?.user?.discordId;

  if (!discordId) {
    redirect("/auth/signin");
  }

  const envAdmin = process.env.ADMIN_DISCORD_ID;
  const adminRecord = envAdmin && envAdmin === discordId
    ? null
    : await db.admin.findUnique({ where: { discordId } });

  if (!adminRecord && (!envAdmin || envAdmin !== discordId)) {
    redirect("/");
  }

  const [grades, events, admins] = await Promise.all([
    db.grade.findMany({ orderBy: { price: "asc" } }),
    db.event.findMany({ orderBy: { eventDate: "asc" } }),
    db.admin.findMany({
      orderBy: { createdAt: "desc" },
      include: { user: true },
    }),
  ] as const);

  const adminUsers = admins as AdminWithUser[];
  const gradeRecords = grades as GradeRecord[];
  const eventRecords = events as EventRecord[];

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-6xl flex-1 px-6 py-16">
        <div className="mb-10">
          <p className="text-xs uppercase tracking-[0.4em] text-cyan-200/80">
            Admin panel
          </p>
          <h1 className="mt-4 text-3xl font-semibold text-white md:text-4xl">
            Control center
          </h1>
          <p className="mt-3 text-sm text-slate-300">
            Manage admins, grades, and events for BinouzUHC.
          </p>
        </div>
        <AdminDashboard
          initialAdmins={adminUsers.map((admin) => ({
            id: admin.id,
            discordId: admin.discordId,
            user: admin.user
              ? {
                  name: admin.user.name,
                  email: admin.user.email,
                  discordUsername: admin.user.discordUsername,
                }
              : null,
          }))}
          initialGrades={gradeRecords}
          initialEvents={eventRecords.map((event) => ({
            id: event.id,
            title: event.title,
            description: event.description,
            eventDate: event.eventDate.toISOString(),
          }))}
        />
      </main>
      <Footer />
    </div>
  );
}
