import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { ProfileForm } from "@/app/profil/ProfileForm";
import { CancelSubscriptionButton } from "@/app/profil/CancelSubscriptionButton";

export const dynamic = "force-dynamic";
export const metadata = { title: "Mon profil — Diabetix" };

export default async function ProfilPage() {
  const session = await auth();
  if (!session?.user?.id) redirect("/auth/login");
  const userId = session.user.id;

  const patient = await prisma.patient.findUnique({ where: { userId } });
  const user = await prisma.user.findUnique({ where: { id: userId } });
  const subscription = await prisma.subscription.findUnique({
    where: { userId },
  });

  return (
    <div className="mx-auto max-w-5xl space-y-4">
      <div>
        <h1 className="text-2xl font-semibold text-slate-900">Mon profil</h1>
        <p className="mt-1 text-sm text-slate-500">Vos informations personnelles et médicales.</p>
      </div>
      <ProfileForm
        initial={
          patient
            ? {
                firstName: patient.firstName,
                lastName: patient.lastName,
                email: patient.email,
                birthDate: patient.birthDate ? patient.birthDate.toISOString().split("T")[0] : null,
                heightCm: patient.heightCm,
                weightKg: patient.weightKg,
                sex: patient.sex,
                diabetesType: patient.diabetesType,
                treatment: patient.treatment,
              }
            : null
        }
      />
      <CancelSubscriptionButton
        isPremium={user?.plan === "PREMIUM"}
        subscriptionEndDate={subscription?.currentPeriodEnd}
        isScheduledForCancellation={subscription?.status === "canceled"}
      />
    </div>
  );
}
