"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { User, X, Plus, Search, Loader2 } from "lucide-react";
import { Button } from "./button.js";
import { Input } from "./input.js";
import { Badge } from "./badge.js";
import { Card, CardContent } from "./card.js";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "./dialog.js";
import { Avatar, AvatarFallback, AvatarImage } from "./avatar.js";
import { cn } from "../../lib/utils/index.js";
import { useTeam } from "../../hooks/useTeam.js";
function UserSelect({
  value = [],
  onChange,
  multiple = false,
  maxUsers,
  disabled = false,
  className,
  placeholder = "Seleccionar usuarios...",
  searchPlaceholder = "Buscar usuarios...",
  onSearch,
  onCreate,
  allowCreate = false,
  roleFilter = [],
  teamId
}) {
  const [open, setOpen] = React.useState(false);
  const [searchQuery, setSearchQuery] = React.useState("");
  const [searchResults, setSearchResults] = React.useState([]);
  const [isSearching, setIsSearching] = React.useState(false);
  const [teamMembers, setTeamMembers] = React.useState([]);
  const [isLoadingMembers, setIsLoadingMembers] = React.useState(true);
  const [resolvedValue, setResolvedValue] = React.useState([]);
  const { teamId: contextTeamId } = useTeam();
  const effectiveTeamId = teamId || contextTeamId;
  React.useEffect(() => {
    if (!effectiveTeamId) {
      setIsLoadingMembers(false);
      return;
    }
    setIsLoadingMembers(true);
    const fetchTeamMembers = async () => {
      try {
        const response = await fetch(`/api/v1/teams/${effectiveTeamId}/members`);
        if (!response.ok) {
          console.error("Failed to fetch team members");
          return;
        }
        const data = await response.json();
        if (data.success && Array.isArray(data.data)) {
          const users = data.data.map((member) => {
            const nameParts = (member.userName || "").split(" ");
            const firstName = nameParts[0] || member.userEmail.split("@")[0];
            const lastName = nameParts.slice(1).join(" ") || void 0;
            return {
              id: member.userId,
              firstName,
              lastName,
              email: member.userEmail,
              avatar: member.userImage || void 0,
              role: member.role
            };
          });
          setTeamMembers(users);
        }
      } catch (error) {
        console.error("Error fetching team members:", error);
      } finally {
        setIsLoadingMembers(false);
      }
    };
    fetchTeamMembers();
  }, [effectiveTeamId]);
  React.useEffect(() => {
    if (value.length === 0) {
      setResolvedValue([]);
      return;
    }
    const resolved = value.map((v) => {
      if (typeof v === "object" && v.firstName) {
        return v;
      }
      const userId = typeof v === "object" ? v.id : v;
      const found = teamMembers.find((m) => m.id === userId);
      if (found) {
        return found;
      }
      return {
        id: userId,
        firstName: String(userId).slice(0, 8) + "...",
        email: ""
      };
    });
    setResolvedValue(resolved);
  }, [value, teamMembers]);
  const stableRoleFilter = React.useMemo(() => {
    if (!roleFilter || roleFilter.length === 0) return [];
    return [...roleFilter].sort();
  }, [roleFilter]);
  const filteredUsers = React.useMemo(() => {
    let users = teamMembers;
    if (stableRoleFilter.length > 0) {
      users = users.filter((user) => user.role && stableRoleFilter.includes(user.role));
    }
    if (searchQuery.trim()) {
      const queryLower = searchQuery.toLowerCase();
      users = users.filter((user) => {
        const fullName = `${user.firstName} ${user.lastName || ""}`.toLowerCase();
        const email = user.email.toLowerCase();
        return fullName.includes(queryLower) || email.includes(queryLower);
      });
    }
    return users;
  }, [teamMembers, stableRoleFilter, searchQuery]);
  React.useEffect(() => {
    if (!onSearch || !open) return;
    const timeoutId = setTimeout(async () => {
      setIsSearching(true);
      try {
        const results = await onSearch(searchQuery);
        setSearchResults(results);
      } catch (error) {
        console.error("Search error:", error);
        setSearchResults([]);
      } finally {
        setIsSearching(false);
      }
    }, 300);
    return () => clearTimeout(timeoutId);
  }, [searchQuery, open, onSearch]);
  const displayUsers = onSearch ? searchResults : filteredUsers;
  const handleSelect = React.useCallback((user) => {
    if (disabled) return;
    if (multiple) {
      const isSelected2 = resolvedValue.some((v) => v.id === user.id);
      if (isSelected2) {
        const newIds = resolvedValue.filter((v) => v.id !== user.id).map((v) => v.id);
        onChange(newIds);
      } else {
        if (maxUsers && resolvedValue.length >= maxUsers) return;
        const newIds = [...resolvedValue.map((v) => v.id), user.id];
        onChange(newIds);
      }
    } else {
      onChange(user.id);
      setOpen(false);
    }
  }, [disabled, multiple, resolvedValue, onChange, maxUsers]);
  const handleRemove = React.useCallback((userId) => {
    if (disabled) return;
    const remainingIds = resolvedValue.filter((user) => user.id !== userId).map((user) => user.id);
    if (!multiple && remainingIds.length === 0) {
      onChange(null);
    } else if (!multiple) {
      onChange(remainingIds[0] || null);
    } else {
      onChange(remainingIds);
    }
  }, [disabled, onChange, resolvedValue, multiple]);
  const isSelected = React.useCallback((user) => {
    return resolvedValue.some((v) => v.id === user.id);
  }, [resolvedValue]);
  const getInitials = React.useCallback((user) => {
    var _a, _b;
    const first = ((_a = user.firstName) == null ? void 0 : _a[0]) || "";
    const last = ((_b = user.lastName) == null ? void 0 : _b[0]) || "";
    return (first + last).toUpperCase() || "?";
  }, []);
  const getDisplayName = React.useCallback((user) => {
    return user.lastName ? `${user.firstName} ${user.lastName}` : user.firstName;
  }, []);
  const getRoleColor = React.useCallback((role) => {
    switch (role) {
      case "owner":
        return "bg-purple-100 text-purple-800";
      case "admin":
        return "bg-red-100 text-red-800";
      case "colaborator":
        return "bg-blue-100 text-blue-800";
      case "member":
        return "bg-green-100 text-green-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  }, []);
  const handleOpenChange = React.useCallback((newOpen) => {
    if (newOpen && isLoadingMembers && !onSearch) {
      return;
    }
    setOpen(newOpen);
    if (!newOpen) {
      setSearchQuery("");
    }
  }, [isLoadingMembers, onSearch]);
  return /* @__PURE__ */ jsxs("div", { className: cn("w-full space-y-2", className), children: [
    resolvedValue.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: resolvedValue.map((user) => /* @__PURE__ */ jsxs(
      Badge,
      {
        variant: "secondary",
        className: "text-xs flex items-center gap-2 py-1 px-2",
        children: [
          /* @__PURE__ */ jsxs(Avatar, { className: "w-4 h-4", children: [
            /* @__PURE__ */ jsx(AvatarImage, { src: user.avatar, alt: getDisplayName(user) }),
            /* @__PURE__ */ jsx(AvatarFallback, { className: "text-xs", children: getInitials(user) })
          ] }),
          /* @__PURE__ */ jsx("span", { className: "truncate max-w-[100px]", children: getDisplayName(user) }),
          !disabled && /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => handleRemove(user.id),
              className: "ml-1 ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
              children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3 text-muted-foreground hover:text-foreground" })
            }
          )
        ]
      },
      user.id
    )) }),
    /* @__PURE__ */ jsxs(Dialog, { open, onOpenChange: handleOpenChange, children: [
      /* @__PURE__ */ jsx(DialogTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
        Button,
        {
          variant: "outline",
          className: cn(
            "w-full justify-start",
            disabled && "opacity-50 cursor-not-allowed"
          ),
          disabled: disabled || !!(maxUsers && resolvedValue.length >= maxUsers),
          children: isLoadingMembers ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
            "Cargando..."
          ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(User, { className: "mr-2 h-4 w-4" }),
            resolvedValue.length > 0 ? `${resolvedValue.length} usuario${resolvedValue.length > 1 ? "s" : ""} seleccionado${resolvedValue.length > 1 ? "s" : ""}` : placeholder
          ] })
        }
      ) }),
      /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-md", children: [
        /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: "Seleccionar Usuarios" }) }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "relative", children: [
            /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" }),
            /* @__PURE__ */ jsx(
              Input,
              {
                placeholder: searchPlaceholder,
                value: searchQuery,
                onChange: (e) => setSearchQuery(e.target.value),
                className: "pl-9"
              }
            )
          ] }),
          stableRoleFilter.length > 0 && /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
            "Filtrando por roles: ",
            stableRoleFilter.join(", ")
          ] }),
          allowCreate && onCreate && /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "outline",
              className: "w-full",
              onClick: onCreate,
              children: [
                /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
                "Invitar nuevo usuario"
              ]
            }
          ),
          /* @__PURE__ */ jsx("div", { className: "max-h-60 overflow-auto space-y-2", children: isSearching ? /* @__PURE__ */ jsxs("div", { className: "text-center text-muted-foreground py-4", children: [
            /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin inline mr-2" }),
            "Buscando usuarios..."
          ] }) : displayUsers.length > 0 ? displayUsers.map((user) => /* @__PURE__ */ jsx(
            Card,
            {
              className: cn(
                "cursor-pointer transition-colors hover:bg-muted",
                isSelected(user) && "bg-primary/10 border-primary"
              ),
              onClick: () => handleSelect(user),
              children: /* @__PURE__ */ jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                /* @__PURE__ */ jsxs(Avatar, { className: "w-8 h-8", children: [
                  /* @__PURE__ */ jsx(AvatarImage, { src: user.avatar, alt: getDisplayName(user) }),
                  /* @__PURE__ */ jsx(AvatarFallback, { className: "text-xs", children: getInitials(user) })
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
                  /* @__PURE__ */ jsx("p", { className: "text-sm font-medium truncate", children: getDisplayName(user) }),
                  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground truncate", children: user.email }),
                  user.role && /* @__PURE__ */ jsx(
                    Badge,
                    {
                      variant: "secondary",
                      className: cn("text-xs mt-1", getRoleColor(user.role)),
                      children: user.role
                    }
                  )
                ] }),
                isSelected(user) && /* @__PURE__ */ jsx("div", { className: "text-primary", children: "\u2713" })
              ] }) })
            },
            user.id
          )) : /* @__PURE__ */ jsx("div", { className: "text-center text-muted-foreground py-4", children: searchQuery ? "No se encontraron usuarios" : "No hay usuarios disponibles" }) })
        ] })
      ] })
    ] })
  ] });
}
export {
  UserSelect
};
