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

type Org = { id: string; name: string };

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();

  let orgs: Org[] = [];

  if (me?.is_staff) {
    const { data: orgsData } = await sb
      .from("organizations")
      .select("id,name")
      .order("name", { ascending: true });
    orgs = (orgsData as Org[]) || [];
  } else {
    const { data: myOrg } = await sb.rpc("get_my_org").maybeSingle();

    if (myOrg) {
      orgs = [{ id: (myOrg as Org).id, name: (myOrg as Org).name }];
    } else {
      const { data: orgMembers } = await sb
        .from("organization_members")
        .select("organizations(id,name)")
        .eq("user_id", user.id)
        .eq("revoked", false);

      const typedMembers = (orgMembers as { organizations: Org | null }[] | null) ?? null;

      if (typedMembers) {
        const mappedOrgs = typedMembers
          .map((m) => m.organizations)
          .filter((o): o is Org => o !== null);

        const uniqueOrgsMap = new Map<string, Org>();
        for (const o of mappedOrgs) {
          if (!uniqueOrgsMap.has(o.id)) uniqueOrgsMap.set(o.id, o);
        }
        orgs = Array.from(uniqueOrgsMap.values());
      }
    }
  }

  return { isStaff: !!me?.is_staff, orgs } as { isStaff: boolean; orgs: Org[] };
}

export default async function Page() {
  const { orgs } = await getContext();
  const singleOrg: Org | null = orgs.length === 1 ? orgs[0] : null;

  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>
        {singleOrg ? (
          <InviteForm orgs={orgs} defaultOrgId={singleOrg.id} hideOrgSelect />
        ) : (
          <InviteForm orgs={orgs} />
        )}
      </Suspense>
    </div>
  );
}