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 CreateStaffForm from "@/components/staff/CreateStaffForm";
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, isSuperStaff: false, orgs: [] };

  const { data: me } = await sb
    .from("staff_users")
    .select("is_staff, super_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, 
    isSuperStaff: !!me?.super_staff,
    orgs: orgs || [] 
  };
}

export default async function Page({ searchParams }: { searchParams: { type?: string } }) {
  const { isStaff, isSuperStaff, 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>
    );
  }

  const type = searchParams.type || 'client';

  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>

      {/* Onglets pour choisir le type d'utilisateur */}
      <div className="mb-6 flex gap-2 border-b border-slate-200">
        <Link 
          href="/staff/utilisateurs/nouveau?type=client"
          className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
            type === 'client' 
              ? 'border-indigo-600 text-indigo-600' 
              : 'border-transparent text-slate-600 hover:text-slate-900'
          }`}
        >
          Utilisateur Client
        </Link>
        {isSuperStaff && (
          <Link 
            href="/staff/utilisateurs/nouveau?type=staff"
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
              type === 'staff' 
                ? 'border-indigo-600 text-indigo-600' 
                : 'border-transparent text-slate-600 hover:text-slate-900'
            }`}
          >
            Utilisateur Staff
          </Link>
        )}
      </div>

      <Suspense>
        {type === 'staff' && isSuperStaff ? (
          <CreateStaffForm isSuperStaff={isSuperStaff} />
        ) : (
          <InviteForm orgs={orgs} />
        )}
      </Suspense>
    </div>
  );
}