"use client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTeam } from "./useTeam.js";
function useTeamMembers(options) {
  const { teamId: contextTeamId } = useTeam();
  const teamId = (options == null ? void 0 : options.teamId) || contextTeamId;
  const queryClient = useQueryClient();
  const { data: members = [], isLoading } = useQuery({
    queryKey: ["team-members", teamId],
    queryFn: async () => {
      if (!teamId) return [];
      const response = await fetch(`/api/v1/teams/${teamId}/members`);
      if (!response.ok) throw new Error("Failed to fetch members");
      const json = await response.json();
      const rawMembers = json.data || [];
      return rawMembers.map((member) => ({
        ...member,
        // Create nested user object from flat properties
        user: {
          id: member.userId,
          name: member.userName,
          email: member.userEmail,
          image: member.userImage,
          avatarUrl: member.userImage
        }
      }));
    },
    enabled: !!teamId
  });
  const inviteMemberMutation = useMutation({
    mutationFn: async (request) => {
      const response = await fetch(`/api/v1/teams/${teamId}/members`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(request)
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || "Failed to invite member");
      }
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["team-members", teamId] });
      queryClient.invalidateQueries({ queryKey: ["team-invitations", teamId] });
    }
  });
  const updateMemberRoleMutation = useMutation({
    mutationFn: async ({ memberId, role }) => {
      const response = await fetch(`/api/v1/teams/${teamId}/members/${memberId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ role })
      });
      if (!response.ok) throw new Error("Failed to update role");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["team-members", teamId] });
    }
  });
  const removeMemberMutation = useMutation({
    mutationFn: async (memberId) => {
      const response = await fetch(`/api/v1/teams/${teamId}/members/${memberId}`, {
        method: "DELETE"
      });
      if (!response.ok) throw new Error("Failed to remove member");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["team-members", teamId] });
    }
  });
  return {
    members,
    isLoading,
    inviteMember: inviteMemberMutation.mutate,
    inviteMemberAsync: inviteMemberMutation.mutateAsync,
    isInviting: inviteMemberMutation.isPending,
    updateMemberRole: updateMemberRoleMutation.mutate,
    isUpdatingRole: updateMemberRoleMutation.isPending,
    removeMember: removeMemberMutation.mutate,
    isRemovingMember: removeMemberMutation.isPending
  };
}
export {
  useTeamMembers
};
