"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { MoreHorizontal, Crown, Shield, Eye, UserMinus, Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { formatDistanceToNow } from "date-fns";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "../ui/table.js";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from "../ui/dropdown-menu.js";
import { Button } from "../ui/button.js";
import { Badge } from "../ui/badge.js";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar.js";
import { useTeamMembers } from "../../hooks/useTeamMembers.js";
import { useTeam } from "../../hooks/useTeam.js";
import { useAuth } from "../../hooks/useAuth.js";
import { InviteMemberDialog } from "./InviteMemberDialog.js";
import { APP_CONFIG_MERGED } from "../../lib/config/config-sync.js";
import { canManageRole } from "../../lib/teams/permissions.js";
const roleIconsMap = {
  owner: Crown,
  admin: Shield,
  member: null,
  viewer: Eye
};
const roleColorsMap = {
  owner: "destructive",
  admin: "default",
  member: "secondary",
  viewer: "outline"
};
const getRoleIcon = (role) => roleIconsMap[role] ?? Eye;
const getRoleColor = (role) => roleColorsMap[role] ?? "outline";
function TeamMembersList({ teamId: propTeamId, readOnly = false } = {}) {
  const t = useTranslations("teams");
  const { user } = useAuth();
  const { team } = useTeam();
  const { members, isLoading, updateMemberRole, removeMember } = useTeamMembers({ teamId: propTeamId });
  const [showInviteDialog, setShowInviteDialog] = useState(false);
  if (isLoading) {
    return /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center p-8 gap-3", children: [
      /* @__PURE__ */ jsx(Loader2, { className: "h-6 w-6 animate-spin text-muted-foreground" }),
      /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: t("messages.loading") })
    ] });
  }
  const currentUserMember = members.find((m) => m.userId === (user == null ? void 0 : user.id) || m.user_id === (user == null ? void 0 : user.id));
  const currentUserRole = (currentUserMember == null ? void 0 : currentUserMember.role) || "viewer";
  const canManageMembers = !readOnly && currentUserMember && ["owner", "admin"].includes(currentUserMember.role);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex justify-between items-center", children: [
      /* @__PURE__ */ jsxs("h3", { className: "text-lg font-semibold", children: [
        t("entity.plural"),
        " (",
        members.length,
        ")"
      ] }),
      canManageMembers && /* @__PURE__ */ jsx(
        Button,
        {
          onClick: () => setShowInviteDialog(true),
          "data-cy": "invite-member-button",
          children: t("actions.invite")
        }
      )
    ] }),
    /* @__PURE__ */ jsx("div", { className: "border rounded-md", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: t("fields.name") }),
        /* @__PURE__ */ jsx(TableHead, { children: t("fields.role") }),
        /* @__PURE__ */ jsx(TableHead, { children: t("fields.joinedAt") }),
        canManageMembers && /* @__PURE__ */ jsx(TableHead, { className: "w-10" })
      ] }) }),
      /* @__PURE__ */ jsx(TableBody, { children: members.map((member) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _i;
        const memberRole = member.role;
        const RoleIcon = getRoleIcon(memberRole);
        const isOwner = memberRole === "owner";
        const isCurrentUser = member.userId === (user == null ? void 0 : user.id) || member.user_id === (user == null ? void 0 : user.id);
        return /* @__PURE__ */ jsxs(TableRow, { "data-cy": `member-row-${member.userId || member.user_id}`, children: [
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
            /* @__PURE__ */ jsxs(Avatar, { className: "h-8 w-8", children: [
              /* @__PURE__ */ jsx(AvatarImage, { src: ((_a = member.user) == null ? void 0 : _a.avatarUrl) || ((_b = member.user) == null ? void 0 : _b.avatar_url), alt: (_c = member.user) == null ? void 0 : _c.name }),
              /* @__PURE__ */ jsx(AvatarFallback, { children: (((_e = (_d = member.user) == null ? void 0 : _d.name) == null ? void 0 : _e[0]) || ((_g = (_f = member.user) == null ? void 0 : _f.email) == null ? void 0 : _g[0]) || "?").toUpperCase() })
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("div", { className: "font-medium", children: ((_h = member.user) == null ? void 0 : _h.name) || "Unknown" }),
              /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: (_i = member.user) == null ? void 0 : _i.email })
            ] })
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs(Badge, { variant: getRoleColor(memberRole), children: [
            RoleIcon && /* @__PURE__ */ jsx(RoleIcon, { className: "h-3 w-3 mr-1", "aria-hidden": "true" }),
            t(`roles.${memberRole}`)
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: formatDistanceToNow(new Date(member.joinedAt || member.joined_at), {
            addSuffix: true
          }) }) }),
          canManageMembers && /* @__PURE__ */ jsx(TableCell, { children: !isOwner && !isCurrentUser && /* @__PURE__ */ jsxs(DropdownMenu, { children: [
            /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", "data-cy": `member-actions-${member.id}`, children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" }) }) }),
            /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", children: [
              APP_CONFIG_MERGED.teamRoles.availableTeamRoles.filter(
                (role) => role !== "owner" && // Cannot assign owner role
                role !== memberRole && // Don't show current role
                canManageRole(currentUserRole, role)
                // Only roles user can manage
              ).map((role) => {
                const roleLabel = t(`roles.${role}`, { defaultValue: role.charAt(0).toUpperCase() + role.slice(1) });
                return /* @__PURE__ */ jsx(
                  DropdownMenuItem,
                  {
                    onClick: () => updateMemberRole({
                      memberId: member.id,
                      role
                    }),
                    "data-cy": `make-${role}-action`,
                    children: t("actions.makeRole", { role: roleLabel })
                  },
                  role
                );
              }),
              /* @__PURE__ */ jsxs(
                DropdownMenuItem,
                {
                  onClick: () => removeMember(member.id),
                  className: "text-destructive",
                  "data-cy": "remove-member-action",
                  children: [
                    /* @__PURE__ */ jsx(UserMinus, { className: "h-4 w-4 mr-2", "aria-hidden": "true" }),
                    t("actions.removeMember")
                  ]
                }
              )
            ] })
          ] }) })
        ] }, member.id);
      }) })
    ] }) }),
    !readOnly && /* @__PURE__ */ jsx(
      InviteMemberDialog,
      {
        open: showInviteDialog,
        onOpenChange: setShowInviteDialog,
        teamId: propTeamId,
        currentUserRole
      }
    )
  ] });
}
export {
  TeamMembersList
};
