import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { GrantAccess, RevokeAccess } from "@/components/features/accounts";
import { Badge, Card, CardHeader, EmptyState, PageHeader, StatusBadge, Table, Td, Th } from "@/components/ui";
import { canAnywhere } from "@/lib/authz/context";
import { requireDashboard } from "@/lib/authz/guard";
import { listAccess } from "@/lib/services/workspace";

export const metadata: Metadata = { title: "Users & permissions" };
export const dynamic = "force-dynamic";

export default async function UsersPage() {
  const ctx = await requireDashboard("admin");
  if (!canAnywhere(ctx, "users.manage")) notFound();
  const { orgRows, siteRows, sites } = await listAccess(ctx);
  return (
    <>
      <PageHeader title="Users & permissions" description="Who can work on your websites. You can grant Editor or Maintenance access to people who already have an account; platform staff create accounts and organization administrators." />
      {sites.length > 0 ? <GrantAccess sites={sites.map((s) => ({ id: s.id, name: s.name, organization: s.organization.name }))} /> : null}
      <Card className="mb-4">
        <CardHeader title="Organization administrators" />
        {orgRows.length === 0 ? <EmptyState title="None" /> : (
          <Table><thead><tr><Th>Person</Th><Th>Organization</Th><Th>Role</Th><Th>Account</Th></tr></thead>
            <tbody>{orgRows.map((m) => <tr key={m.id}><Td>{m.user.name}<div className="text-xs text-muted-foreground">{m.user.email}</div></Td><Td>{m.organization.name}</Td><Td><Badge tone="info">{m.role.name}</Badge></Td><Td><StatusBadge value={m.user.status} /></Td></tr>)}</tbody></Table>
        )}
      </Card>
      <Card>
        <CardHeader title="Website access" />
        {siteRows.length === 0 ? <EmptyState title="No one has website-level access yet" /> : (
          <Table><thead><tr><Th>Person</Th><Th>Website</Th><Th>Role</Th><Th>Account</Th><Th><span className="sr-only">Actions</span></Th></tr></thead>
            <tbody>{siteRows.map((m) => <tr key={m.id}><Td>{m.user.name}<div className="text-xs text-muted-foreground">{m.user.email}</div></Td><Td>{m.site.name}</Td><Td>{m.role.name}</Td><Td><StatusBadge value={m.user.status} /></Td><Td>{m.user.id === ctx.userId ? <span className="text-xs text-muted-foreground">You</span> : <RevokeAccess membershipId={m.id} label={`${m.user.name} on ${m.site.name}`} />}</Td></tr>)}</tbody></Table>
        )}
      </Card>
    </>
  );
}
