export const dynamic = "force-dynamic";

import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { Query } from "node-appwrite";

import { createAdminClient } from "@/lib/appwrite/server";
import { DATABASE_ID, TABLES, type InviteLink } from "@/lib/appwrite/schema";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { InviteForm } from "./components/invite-form";
import { MembersTable } from "./components/members-table";
import { PendingInvitesTable } from "./components/pending-invites-table";

export const metadata: Metadata = {
  title: "İşletmem — Ekip üyeleri",
};

export default async function MembersPage() {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  if (ctx.role === "member") redirect("/dashboard");

  const canManage = ctx.role === "owner" || ctx.role === "admin";
  const isOwner = ctx.role === "owner";

  const { teams, tablesDB } = createAdminClient();

  const [memberships, invites] = await Promise.all([
    teams.listMemberships(ctx.tenantId).catch(() => ({ memberships: [], total: 0 })),
    tablesDB
      .listRows({
        databaseId: DATABASE_ID,
        tableId: TABLES.inviteLinks,
        queries: [
          Query.equal("tenantId", ctx.tenantId),
          Query.equal("status", "pending"),
          Query.orderDesc("$createdAt"),
          Query.limit(50),
        ],
      })
      .catch(() => ({ rows: [] as unknown[] })),
  ]);

  const members = memberships.memberships.map((m) => ({
    id: m.$id,
    userId: m.userId,
    name: m.userName || m.userEmail,
    email: m.userEmail,
    role: m.roles[0] ?? "member",
    joined: m.joined,
    invited: m.invited,
    confirm: m.confirm,
  }));

  const pendingInvites = (invites.rows as unknown as InviteLink[]).map((row) => ({
    id: row.$id,
    code: row.code,
    email: row.email,
    role: row.role ?? "member",
    expiresAt: row.expiresAt,
    createdAt: row.$createdAt,
  }));

  return (
    <div className="flex-1 space-y-6 px-6 pt-4">
      <div className="flex flex-col gap-1">
        <p className="text-muted-foreground text-sm">{ctx.settings?.officeName ?? "Çalışma alanı"}</p>
        <h1 className="text-2xl font-bold tracking-tight">Ekip üyeleri</h1>
        <p className="text-muted-foreground text-sm">
          Çalışma alanına üye davet edin, rolleri yönetin.
        </p>
      </div>

      {canManage ? (
        <InviteForm />
      ) : (
        <p className="text-muted-foreground text-sm">
          Yeni üye davet etmek için yönetici yetkisine ihtiyacınız var.
        </p>
      )}

      {pendingInvites.length > 0 && (
        <PendingInvitesTable invites={pendingInvites} canManage={canManage} />
      )}

      <MembersTable
        members={members}
        currentUserId={ctx.user.id}
        isOwner={isOwner}
        canManage={canManage}
      />
    </div>
  );
}
