"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Avatar, AvatarFallback, AvatarImage } from "./avatar";
import { Badge } from "./badge";
import { cn } from "../../lib/utils";
import { useTeam } from "../../hooks/useTeam";
function UserDisplay({
  value,
  teamId: propTeamId,
  showRole = false,
  showEmail = false,
  className
}) {
  const [userData, setUserData] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const { teamId: contextTeamId } = useTeam();
  const effectiveTeamId = propTeamId || contextTeamId;
  const loadedRef = React.useRef({ userId: null, teamId: null });
  React.useEffect(() => {
    if (!value || !effectiveTeamId) {
      if (!value) {
        setUserData(null);
        loadedRef.current = { userId: null, teamId: null };
      }
      return;
    }
    if (value === loadedRef.current.userId && effectiveTeamId === loadedRef.current.teamId) {
      return;
    }
    const fetchUser = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(`/api/v1/teams/${effectiveTeamId}/members`, {
          headers: {
            "Content-Type": "application/json",
            "x-team-id": effectiveTeamId
          },
          credentials: "include"
        });
        if (response.ok) {
          const result = await response.json();
          if (result.success && Array.isArray(result.data)) {
            const member = result.data.find((m) => m.userId === value);
            if (member) {
              setUserData({
                id: member.userId,
                name: member.userName,
                email: member.userEmail,
                image: member.userImage,
                role: member.role
              });
              loadedRef.current = { userId: value, teamId: effectiveTeamId };
            } else {
              setError("Usuario no encontrado");
            }
          }
        } else {
          setError("Error al cargar usuario");
        }
      } catch (err) {
        console.error("[UserDisplay] Error fetching user:", err);
        setError("Error al cargar usuario");
      } finally {
        setLoading(false);
      }
    };
    fetchUser();
  }, [value, effectiveTeamId]);
  if (!value) {
    return /* @__PURE__ */ jsx("span", { className: cn("text-muted-foreground", className), children: "-" });
  }
  if (loading) {
    return /* @__PURE__ */ jsx("span", { className: cn("text-muted-foreground", className), children: "Cargando..." });
  }
  if (error || !userData) {
    return /* @__PURE__ */ jsx("span", { className: cn("text-muted-foreground", className), children: value });
  }
  const getInitials = (name) => {
    var _a, _b;
    if (!name) return "?";
    const parts = name.split(" ");
    const first = ((_a = parts[0]) == null ? void 0 : _a[0]) || "";
    const last = ((_b = parts[1]) == null ? void 0 : _b[0]) || "";
    return (first + last).toUpperCase() || "?";
  };
  const getRoleColor = (role) => {
    switch (role) {
      case "owner":
        return "bg-purple-100 text-purple-800";
      case "admin":
        return "bg-red-100 text-red-800";
      case "member":
        return "bg-green-100 text-green-800";
      case "viewer":
        return "bg-blue-100 text-blue-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: cn("flex items-center gap-2", className), children: [
    /* @__PURE__ */ jsxs(Avatar, { className: "h-6 w-6", children: [
      /* @__PURE__ */ jsx(AvatarImage, { src: userData.image || void 0, alt: userData.name || "User" }),
      /* @__PURE__ */ jsx(AvatarFallback, { className: "text-xs", children: getInitials(userData.name) })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
      /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: userData.name || userData.email }),
      showEmail && userData.name && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: userData.email })
    ] }),
    showRole && userData.role && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: cn("text-xs ml-2", getRoleColor(userData.role)), children: userData.role })
  ] });
}
export {
  UserDisplay
};
