import { canSee } from "@/lib/session";
import { getPortalSession } from "@/lib/get-session";
import { loadTenantForShell } from "@/lib/portal-data";
import { Panel } from "@/components/portal/Panel";
import { NotAllowed } from "@/components/portal/NotAllowed";
import { InviteButton } from "@/components/portal/InviteButton";

export default async function TeamPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const session = await getPortalSession();
  if (!canSee(session, "users")) return <NotAllowed need="IT_ADMIN" />;
  const t = await loadTenantForShell(slug);
  if (!t) return null;
  const team = t.team;

  return (
    <div className="content-inner">
      <div className="page-head">
        <div>
          <div className="page-title">Team</div>
          <div className="page-sub">
            {team.length} members ·{" "}
            <span className="mono">{t.seats.used}/{t.seats.total}</span> seats used
          </div>
        </div>
        <div className="ph-actions">
          <button type="button" className="btn">Export</button>
          <InviteButton tenantStatus={t.status} />
        </div>
      </div>

      <Panel bracket pad={false}>
        <table className="ltable">
          <thead>
            <tr>
              <th>Member</th>
              <th>Email</th>
              <th>Roles</th>
              <th>Last active</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {team.map((m, i) => (
              <tr key={i}>
                <td>
                  <span className="row" style={{ gap: 9 }}>
                    <span className="avatar" style={{ width: 24, height: 24, fontSize: 9 }}>
                      {m.name.split(" ").map((s) => s[0]).join("")}
                    </span>
                    <span style={{ fontWeight: 500, whiteSpace: "nowrap" }}>{m.name}</span>
                  </span>
                </td>
                <td className="mono t-dim" style={{ fontSize: 11.5 }}>{m.email}</td>
                <td>
                  <span className="row wrap" style={{ gap: 4 }}>
                    {m.roles.map((r) => (
                      <span key={r} className="role-chip">{r}</span>
                    ))}
                  </span>
                </td>
                <td className="mono t-dim">{m.last}</td>
                <td>
                  <span className="row" style={{ gap: 6, fontSize: 12 }}>
                    <span className={`dot ${m.status === "invited" ? "warn" : "ok"}`} />
                    {m.status === "invited" ? "Invited" : "Active"}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Panel>
    </div>
  );
}
