import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select } from "@/components/ui/select";
import { z } from "zod";

export const dynamic = "force-dynamic";

const schema = z.object({
  firstName: z.string().min(2),
  lastName: z.string().min(2),
  email: z.string().email(),
  classId: z.string().min(1),
});

function generateActivationCode(): string {
  const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  let code = "";
  for (let i = 0; i < 6; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return code;
}

async function createStudent(formData: FormData) {
  "use server";
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login");
  if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");

  const parsed = schema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return;

  await prisma.student.create({
    data: {
      firstName: parsed.data.firstName,
      lastName: parsed.data.lastName,
      email: parsed.data.email,
      classId: parsed.data.classId,
      activationCode: generateActivationCode(),
    },
  });

  redirect("/dashboard/students");
}

export default async function NewStudentPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login");
  if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");

  const establishmentId = session.user.establishmentId;
  const classes = await prisma.class.findMany({
    where: establishmentId ? { establishmentId } : {},
    orderBy: { name: "asc" },
  });

  return (
    <div className="space-y-6 max-w-xl">
      <h1 className="text-3xl font-bold">Nouvel étudiant</h1>
      <Card>
        <CardHeader>
          <CardTitle>Créer un étudiant</CardTitle>
        </CardHeader>
        <CardContent>
          <form action={createStudent} className="space-y-4">
            <div className="space-y-2">
              <label htmlFor="firstName" className="text-sm font-medium">Prénom</label>
              <Input id="firstName" name="firstName" required minLength={2} />
            </div>
            <div className="space-y-2">
              <label htmlFor="lastName" className="text-sm font-medium">Nom</label>
              <Input id="lastName" name="lastName" required minLength={2} />
            </div>
            <div className="space-y-2">
              <label htmlFor="email" className="text-sm font-medium">Email</label>
              <Input id="email" name="email" type="email" required />
            </div>
            <div className="space-y-2">
              <label htmlFor="classId" className="text-sm font-medium">Classe</label>
              <Select id="classId" name="classId" required>
                <option value="">Choisir une classe</option>
                {classes.map((c) => (
                  <option key={c.id} value={c.id}>{c.name} ({c.level})</option>
                ))}
              </Select>
            </div>
            <div className="flex justify-end">
              <Button type="submit">Créer</Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
