"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { formatDistanceToNow } from "date-fns";
import { Trash2, Mail, Clock, Shield, Eye, Crown } from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "../ui/table.js";
import { Button } from "../ui/button.js";
import { Badge } from "../ui/badge.js";
import { Skeleton } from "../ui/skeleton.js";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "../ui/dialog.js";
import { toast } from "sonner";
import { useTeamMembers } from "../../hooks/useTeamMembers.js";
import { useAuth } from "../../hooks/useAuth.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 TeamPendingInvitations({ teamId }) {
  const t = useTranslations("teams");
  const queryClient = useQueryClient();
  const { user } = useAuth();
  const { members } = useTeamMembers({ teamId });
  const [cancellingId, setCancellingId] = useState(null);
  const currentUserMember = members.find((m) => m.userId === (user == null ? void 0 : user.id) || m.user_id === (user == null ? void 0 : user.id));
  const canManageInvitations = currentUserMember && ["owner", "admin"].includes(currentUserMember.role);
  const { data: invitations = [], isLoading } = useQuery({
    queryKey: ["team-invitations", teamId],
    queryFn: async () => {
      const response = await fetch(`/api/v1/teams/${teamId}/invitations?status=pending`);
      if (!response.ok) throw new Error("Failed to fetch invitations");
      const json = await response.json();
      return json.data || [];
    },
    enabled: !!teamId
  });
  const cancelMutation = useMutation({
    mutationFn: async (invitationId) => {
      const response = await fetch(`/api/v1/teams/${teamId}/invitations?id=${invitationId}`, {
        method: "DELETE"
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || "Failed to cancel invitation");
      }
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["team-invitations", teamId] });
      toast.success(t("messages.invitationCancelled"));
      setCancellingId(null);
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : t("errors.unauthorized"));
      setCancellingId(null);
    }
  });
  if (isLoading) {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-4 mt-6", "aria-busy": "true", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsx(Mail, { className: "h-4 w-4 text-muted-foreground" }),
        /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-40" })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "border rounded-md", children: /* @__PURE__ */ jsx("div", { className: "p-4 space-y-3", children: [0, 1].map((i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-40" }),
        /* @__PURE__ */ jsx(Skeleton, { className: "h-5 w-20 rounded-full" }),
        /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-24 ml-auto" })
      ] }, i)) }) })
    ] });
  }
  if (invitations.length === 0) {
    return null;
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4 mt-6", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ jsx(Mail, { className: "h-4 w-4 text-muted-foreground" }),
      /* @__PURE__ */ jsxs("h4", { className: "text-sm font-medium", children: [
        t("invitations.pending"),
        " (",
        invitations.length,
        ")"
      ] })
    ] }),
    /* @__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.email") }),
        /* @__PURE__ */ jsx(TableHead, { children: t("fields.role") }),
        /* @__PURE__ */ jsx(TableHead, { children: t("invitations.invitedBy") }),
        /* @__PURE__ */ jsx(TableHead, { children: t("invitations.expiresAt") }),
        canManageInvitations && /* @__PURE__ */ jsx(TableHead, { className: "w-10" })
      ] }) }),
      /* @__PURE__ */ jsx(TableBody, { children: invitations.map((invitation) => {
        const invitationRole = invitation.role;
        const RoleIcon = getRoleIcon(invitationRole);
        const isExpired = new Date(invitation.expiresAt) < /* @__PURE__ */ new Date();
        return /* @__PURE__ */ jsxs(TableRow, { "data-cy": `invitation-row-${invitation.id}`, children: [
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(Mail, { className: "h-4 w-4 text-muted-foreground" }),
            /* @__PURE__ */ jsx("span", { className: "font-medium", children: invitation.email })
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs(Badge, { variant: getRoleColor(invitationRole), children: [
            RoleIcon && /* @__PURE__ */ jsx(RoleIcon, { className: "h-3 w-3 mr-1", "aria-hidden": "true" }),
            t(`roles.${invitationRole}`)
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: invitation.inviterName || invitation.inviterEmail }) }),
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
            /* @__PURE__ */ jsx(Clock, { className: "h-3 w-3 text-muted-foreground" }),
            /* @__PURE__ */ jsx("span", { className: `text-sm ${isExpired ? "text-destructive" : "text-muted-foreground"}`, children: isExpired ? t("invitations.expired") : formatDistanceToNow(new Date(invitation.expiresAt), { addSuffix: true }) })
          ] }) }),
          canManageInvitations && /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(
            Button,
            {
              variant: "ghost",
              size: "icon",
              onClick: () => setCancellingId(invitation.id),
              disabled: cancelMutation.isPending,
              "data-cy": `cancel-invitation-${invitation.id}`,
              children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-destructive" })
            }
          ) })
        ] }, invitation.id);
      }) })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open: !!cancellingId, onOpenChange: () => setCancellingId(null), children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: t("invitations.cancelTitle") }),
        /* @__PURE__ */ jsx(DialogDescription, { children: t("invitations.cancelDescription") })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            variant: "outline",
            onClick: () => setCancellingId(null),
            disabled: cancelMutation.isPending,
            children: t("actions.cancel")
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            variant: "destructive",
            onClick: () => cancellingId && cancelMutation.mutate(cancellingId),
            disabled: cancelMutation.isPending,
            children: cancelMutation.isPending ? t("messages.cancelling") : t("invitations.cancelConfirm")
          }
        )
      ] })
    ] }) })
  ] });
}
export {
  TeamPendingInvitations
};
