import { cookies } from "next/headers";
import { createSbServer } from "@/lib/supabaseServer";
import Link from "next/link";
import { Suspense } from "react";
import InviteForm from "@/components/staff/InviteForm";
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "Nouvel utilisateur | Espace Paie Odentas",
};

async function getContext() {
  const sb = createSbServer();

  const { data: { user } } = await sb.auth.getUser();
  if (!user) return { isStaff: false, orgs: [] };

  const { data: me } = await sb
    .from("staff_users")
    .select("is_staff")
    .eq("user_id", user.id)
    .maybeSingle();

  const { data: orgs } = await sb
    .from("organizations")
    .select("id,name")
    .order("name", { ascending: true });

  return { isStaff: !!me?.is_staff, orgs: orgs || [] };
}

export default async function Page() {
  const { isStaff, orgs } = await getContext();
  if (!isStaff) {
    return (
      <div className="max-w-3xl mx-auto p-6">
        <h1 className="text-xl font-semibold">Accès refusé</h1>
        <p className="mt-2 text-sm text-slate-600">Cette page est réservée au Staff.</p>
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto p-6">
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-semibold">Nouvel utilisateur</h1>
        <Link href="/staff/utilisateurs" className="text-sm text-slate-600 hover:underline">Retour</Link>
      </div>

      <Suspense>
        <InviteForm orgs={orgs} />
      </Suspense>
    </div>
  );
}