import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { ProfileForm } from "./profile-form";

export default async function ProfilePage() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    redirect("/login");
  }

  const { data: profile } = await supabase
    .from("profiles")
    .select("pseudo, avatar_url, pseudo_locked, role")
    .eq("id", user.id)
    .single();

  const isJudge = profile?.role === "judge";

  return (
    <div className="mx-auto w-full max-w-sm px-4 py-8">
      <div className="mb-6 text-center">
        <h1 className="font-heading text-2xl tracking-[0.1em] text-gold-bright uppercase">
          Mon profil
        </h1>
        <span
          className={`mt-1 inline-block font-heading text-xs tracking-wide uppercase ${
            isJudge ? "text-gold-bright" : "text-marble/50"
          }`}
        >
          {isJudge ? "⚜ Archonte" : "Citoyen"}
        </span>
      </div>
      <div className="marble-surface rounded-2xl border border-gold/40 p-6 shadow-xl sm:p-8">
        <p className="mb-4 text-sm text-text-mut">{user.email}</p>
        <ProfileForm
          userId={user.id}
          isJudge={isJudge}
          initialPseudo={profile?.pseudo ?? ""}
          initialAvatarUrl={profile?.avatar_url ?? null}
          initialPseudoLocked={profile?.pseudo_locked ?? false}
        />
      </div>
    </div>
  );
}
