import { eq } from "drizzle-orm";
import { getTranslations } from "next-intl/server";

import { requireOrgMember } from "@/lib/auth-guards";
import { listMembers, listPendingInvitations } from "@/lib/data/team";
import { db } from "@/lib/db";
import { organization } from "@/lib/db/schema";

import { InviteForm } from "./invite-form";
import { MemberRow } from "./member-row";
import { PendingInvitationRow } from "./pending-invitation-row";

export default async function TeamSettingsPage() {
  const { activeOrganizationId, role, user } = await requireOrgMember({ minRole: "admin" });

  const t = await getTranslations("Settings.team");
  const [orgRow] = await db
    .select({ id: organization.id, name: organization.name })
    .from(organization)
    .where(eq(organization.id, activeOrganizationId))
    .limit(1);
  if (!orgRow) throw new Error("Active organization missing");

  const [members, pending] = await Promise.all([
    listMembers(activeOrganizationId),
    listPendingInvitations(activeOrganizationId),
  ]);

  return (
    <section className="flex flex-col gap-8">
      <div className="flex flex-col gap-1">
        <h2 className="text-xl font-semibold">{t("title")}</h2>
        <p className="text-sm text-muted-foreground">
          {t("description", { orgName: orgRow.name })}
        </p>
      </div>

      <InviteForm />

      <div className="flex flex-col gap-3">
        <h3 className="text-sm font-semibold text-muted-foreground">
          {t("membersTitle", { count: members.length })}
        </h3>
        {members.length === 0 ? (
          <p className="text-sm text-muted-foreground">{t("noMembers")}</p>
        ) : (
          <ul className="flex flex-col gap-1">
            {members.map((m) => (
              <MemberRow
                key={m.id}
                member={{
                  id: m.id,
                  userId: m.userId,
                  name: m.name,
                  email: m.email,
                  role: m.role,
                }}
                viewerRole={role}
                viewerUserId={user.id}
                orgName={orgRow.name}
              />
            ))}
          </ul>
        )}
      </div>

      <div className="flex flex-col gap-3">
        <h3 className="text-sm font-semibold text-muted-foreground">
          {t("pendingTitle", { count: pending.length })}
        </h3>
        {pending.length === 0 ? (
          <p className="text-sm text-muted-foreground">{t("noPending")}</p>
        ) : (
          <ul className="flex flex-col gap-1">
            {pending.map((p) => (
              <PendingInvitationRow key={p.id} invitation={p} />
            ))}
          </ul>
        )}
      </div>
    </section>
  );
}
