"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { format } from "date-fns";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "../../ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem
} from "../../ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "../../ui/dialog";
import { Button } from "../../ui/button";
import { Badge } from "../../ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "../../ui/avatar";
import { useToast } from "../../../hooks/useToast";
import {
  MoreHorizontal,
  User,
  Mail,
  Calendar,
  Eye,
  Edit,
  Ban,
  Trash2,
  CheckCircle,
  UserCheck,
  Loader2
} from "lucide-react";
import { useRoleTranslations } from "../../../lib/role-helpers";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { sel } from "../../../lib/test";
function UsersTable({ users, isLoading, onRefresh }) {
  const getRoleName = useRoleTranslations();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const router = useRouter();
  const handleRowClick = (userId) => {
    router.push(`/superadmin/users/${userId}`);
  };
  const [pendingAction, setPendingAction] = useState(null);
  const actionMutation = useMutation({
    mutationFn: async ({ userId, action, role }) => {
      const response = await fetch(`/api/superadmin/users/${userId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action, role })
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || "Action failed");
      }
      return response.json();
    },
    onSuccess: (data) => {
      toast({
        title: "Success",
        description: data.message || "Action completed successfully"
      });
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      onRefresh == null ? void 0 : onRefresh();
    },
    onError: (error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive"
      });
    }
  });
  const deleteMutation = useMutation({
    mutationFn: async (userId) => {
      const response = await fetch(`/api/superadmin/users/${userId}`, {
        method: "DELETE"
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || "Delete failed");
      }
      return response.json();
    },
    onSuccess: (data) => {
      toast({
        title: "User Deleted",
        description: data.message || "User has been deleted successfully"
      });
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      onRefresh == null ? void 0 : onRefresh();
    },
    onError: (error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive"
      });
    }
  });
  const handleRoleChange = (user, newRole) => {
    if (newRole === user.role) return;
    actionMutation.mutate({ userId: user.id, action: "change-role", role: newRole });
  };
  const handleActionConfirm = () => {
    if (!pendingAction) return;
    const { type, user } = pendingAction;
    switch (type) {
      case "suspend":
        actionMutation.mutate({ userId: user.id, action: "suspend" });
        break;
      case "unsuspend":
        actionMutation.mutate({ userId: user.id, action: "unsuspend" });
        break;
      case "verify-email":
        actionMutation.mutate({ userId: user.id, action: "verify-email" });
        break;
      case "delete":
        deleteMutation.mutate(user.id);
        break;
    }
    setPendingAction(null);
  };
  const getActionDialogContent = () => {
    if (!pendingAction) return { title: "", description: "" };
    const { type, user } = pendingAction;
    const name = user.fullName || user.email;
    switch (type) {
      case "suspend":
        return {
          title: "Suspend User",
          description: `Are you sure you want to suspend ${name}? They will no longer be able to access the application.`
        };
      case "unsuspend":
        return {
          title: "Unsuspend User",
          description: `Are you sure you want to unsuspend ${name}? They will regain access to the application as a member.`
        };
      case "verify-email":
        return {
          title: "Verify Email",
          description: `Are you sure you want to manually verify the email for ${name}?`
        };
      case "delete":
        return {
          title: "Delete User",
          description: `Are you sure you want to permanently delete ${name}? This action cannot be undone. All their data, teams, and memberships will be removed.`
        };
      default:
        return { title: "", description: "" };
    }
  };
  const isMutating = actionMutation.isPending || deleteMutation.isPending;
  const getUserInitials = (user) => {
    if (user.firstName && user.lastName) {
      return `${user.firstName[0]}${user.lastName[0]}`.toUpperCase();
    }
    if (user.firstName) {
      return user.firstName.slice(0, 2).toUpperCase();
    }
    return user.email.slice(0, 2).toUpperCase();
  };
  const getRoleBadgeVariant = (role) => {
    switch (role) {
      case "admin":
        return "destructive";
      case "colaborator":
        return "default";
      case "member":
        return "secondary";
      default:
        return "outline";
    }
  };
  if (isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "space-y-3", children: [...Array(5)].map((_, i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-4 p-4", children: [
      /* @__PURE__ */ jsx("div", { className: "w-10 h-10 bg-muted rounded-full animate-pulse" }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2 flex-1", children: [
        /* @__PURE__ */ jsx("div", { className: "h-4 bg-muted rounded w-1/4 animate-pulse" }),
        /* @__PURE__ */ jsx("div", { className: "h-3 bg-muted rounded w-1/3 animate-pulse" })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "w-20 h-6 bg-muted rounded animate-pulse" }),
      /* @__PURE__ */ jsx("div", { className: "w-8 h-8 bg-muted rounded animate-pulse" })
    ] }, i)) });
  }
  if (users.length === 0) {
    return /* @__PURE__ */ jsxs("div", { className: "text-center py-8", children: [
      /* @__PURE__ */ jsx(User, { className: "mx-auto h-12 w-12 text-muted-foreground" }),
      /* @__PURE__ */ jsx("h3", { className: "mt-4 text-lg font-medium", children: "No users found" }),
      /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-muted-foreground", children: "There are no regular users in the system yet." })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "rounded-md border", "data-cy": sel("superadmin.users.table"), children: [
    /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: "User" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Email" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Role" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Status" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Joined" }),
        /* @__PURE__ */ jsx(TableHead, { className: "text-right", children: "Actions" })
      ] }) }),
      /* @__PURE__ */ jsx(TableBody, { children: users.map((user) => /* @__PURE__ */ jsxs(
        TableRow,
        {
          "data-cy": sel("superadmin.users.row", { id: user.id }),
          className: "cursor-pointer hover:bg-muted/50",
          onClick: () => handleRowClick(user.id),
          children: [
            /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
              /* @__PURE__ */ jsxs(Avatar, { className: "h-9 w-9", children: [
                /* @__PURE__ */ jsx(AvatarImage, { src: "", alt: user.fullName }),
                /* @__PURE__ */ jsx(AvatarFallback, { className: "text-xs", children: getUserInitials(user) })
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("div", { className: "font-medium", children: user.fullName || "No name" }),
                /* @__PURE__ */ jsxs("div", { className: "text-sm text-muted-foreground", children: [
                  "ID: ",
                  user.id.slice(0, 8),
                  "..."
                ] })
              ] })
            ] }) }),
            /* @__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-mono text-sm", children: user.email })
            ] }) }),
            /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(Badge, { variant: getRoleBadgeVariant(user.role), children: getRoleName(user.role) }) }),
            /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2", children: user.emailVerified ? /* @__PURE__ */ jsx(Badge, { variant: "default", className: "bg-green-100 text-green-800", children: "Verified" }) : /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-yellow-600 border-yellow-600", children: "Pending" }) }) }),
            /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
              /* @__PURE__ */ jsx(Calendar, { className: "h-4 w-4" }),
              user.createdAt ? format(new Date(user.createdAt), "MMM dd, yyyy") : "Unknown"
            ] }) }),
            /* @__PURE__ */ jsx(TableCell, { className: "text-right", onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsxs(DropdownMenu, { children: [
              /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  className: "h-8 w-8 p-0",
                  disabled: isMutating,
                  children: [
                    /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Open menu" }),
                    isMutating ? /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" })
                  ]
                }
              ) }),
              /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", children: [
                /* @__PURE__ */ jsx(DropdownMenuLabel, { children: "Actions" }),
                /* @__PURE__ */ jsx(DropdownMenuItem, { asChild: true, children: /* @__PURE__ */ jsxs(Link, { href: `/superadmin/users/${user.id}`, className: "cursor-pointer", children: [
                  /* @__PURE__ */ jsx(Eye, { className: "mr-2 h-4 w-4" }),
                  "View Profile"
                ] }) }),
                /* @__PURE__ */ jsxs(DropdownMenuSub, { children: [
                  /* @__PURE__ */ jsxs(DropdownMenuSubTrigger, { children: [
                    /* @__PURE__ */ jsx(Edit, { className: "mr-2 h-4 w-4" }),
                    "Change Role"
                  ] }),
                  /* @__PURE__ */ jsx(DropdownMenuSubContent, { children: /* @__PURE__ */ jsxs(
                    DropdownMenuRadioGroup,
                    {
                      value: user.role,
                      onValueChange: (value) => handleRoleChange(user, value),
                      children: [
                        /* @__PURE__ */ jsx(DropdownMenuRadioItem, { value: "member", children: "Member" }),
                        /* @__PURE__ */ jsx(DropdownMenuRadioItem, { value: "colaborator", children: "Colaborator" }),
                        /* @__PURE__ */ jsx(DropdownMenuRadioItem, { value: "admin", children: "Admin" })
                      ]
                    }
                  ) })
                ] }),
                !user.emailVerified && /* @__PURE__ */ jsxs(
                  DropdownMenuItem,
                  {
                    className: "cursor-pointer",
                    onClick: () => setPendingAction({ type: "verify-email", user }),
                    children: [
                      /* @__PURE__ */ jsx(CheckCircle, { className: "mr-2 h-4 w-4" }),
                      "Verify Email"
                    ]
                  }
                ),
                /* @__PURE__ */ jsx(DropdownMenuSeparator, {}),
                user.role === "suspended" ? /* @__PURE__ */ jsxs(
                  DropdownMenuItem,
                  {
                    className: "cursor-pointer",
                    onClick: () => setPendingAction({ type: "unsuspend", user }),
                    children: [
                      /* @__PURE__ */ jsx(UserCheck, { className: "mr-2 h-4 w-4" }),
                      "Unsuspend User"
                    ]
                  }
                ) : /* @__PURE__ */ jsxs(
                  DropdownMenuItem,
                  {
                    className: "cursor-pointer text-yellow-600",
                    onClick: () => setPendingAction({ type: "suspend", user }),
                    children: [
                      /* @__PURE__ */ jsx(Ban, { className: "mr-2 h-4 w-4" }),
                      "Suspend User"
                    ]
                  }
                ),
                /* @__PURE__ */ jsxs(
                  DropdownMenuItem,
                  {
                    className: "cursor-pointer text-destructive",
                    onClick: () => setPendingAction({ type: "delete", user }),
                    children: [
                      /* @__PURE__ */ jsx(Trash2, { className: "mr-2 h-4 w-4" }),
                      "Delete User"
                    ]
                  }
                )
              ] })
            ] }) })
          ]
        },
        user.id
      )) })
    ] }),
    /* @__PURE__ */ jsx(Dialog, { open: !!pendingAction, onOpenChange: () => setPendingAction(null), children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: getActionDialogContent().title }),
        /* @__PURE__ */ jsx(DialogDescription, { children: getActionDialogContent().description })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setPendingAction(null), children: "Cancel" }),
        /* @__PURE__ */ jsx(
          Button,
          {
            onClick: handleActionConfirm,
            variant: (pendingAction == null ? void 0 : pendingAction.type) === "delete" ? "destructive" : "default",
            children: (pendingAction == null ? void 0 : pendingAction.type) === "delete" ? "Delete" : "Confirm"
          }
        )
      ] })
    ] }) })
  ] });
}
export {
  UsersTable
};
