import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect, notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { DeleteStudentDialog } from "./DeleteStudentDialog";
import { generateActivationCodeAction } from "./actions";

export const dynamic = "force-dynamic";

export default async function StudentDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  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 student = await prisma.student.findFirst({
    where: {
      id,
      class: establishmentId ? { establishmentId } : undefined,
    },
    include: { class: true },
  });

  if (!student) notFound();

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">{student.firstName} {student.lastName}</h1>
        <DeleteStudentDialog studentId={student.id} studentName={`${student.firstName} ${student.lastName}`} />
      </div>
      <Card>
        <CardContent className="pt-6 space-y-4">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground">Email :</span>
            <span>{student.email}</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground">Classe :</span>
            <Badge variant="secondary">{student.class.name} ({student.class.level})</Badge>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground">Code d'activation :</span>
            {student.activationCode ? (
              <Input value={student.activationCode} readOnly className="w-32 text-center font-mono" />
            ) : (
              <form action={generateActivationCodeAction} className="flex items-center gap-2">
                <input type="hidden" name="id" value={student.id} />
                <Button type="submit" variant="outline" size="sm">Générer code</Button>
              </form>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
