import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { teamApi, type CreateMemberPayload } from "../lib/api/team";
import { useAuthStore } from "../stores/authStore";

const membersKey = () => ["team-members"];
const groupsKey = () => ["team-groups"];

export function useTeamMembers() {
  const isAuthReady = useAuthStore((state) => state.hasHydrated && state.isAuthenticated);
  return useQuery({ queryKey: membersKey(), queryFn: teamApi.listMembers, staleTime: 30_000, enabled: isAuthReady });
}

export function useAddMember() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (payload: CreateMemberPayload) => teamApi.addMember(payload),
    onSuccess: () => qc.invalidateQueries({ queryKey: membersKey() }),
  });
}

export function useUpdateMember() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ userId, patch }: { userId: number; patch: { role?: string; position?: string } }) =>
      teamApi.updateMember(userId, patch),
    onSuccess: () => qc.invalidateQueries({ queryKey: membersKey() }),
  });
}

export function useRemoveMember() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (userId: number) => teamApi.removeMember(userId),
    onSuccess: () => qc.invalidateQueries({ queryKey: membersKey() }),
  });
}

export function useTeamGroups() {
  const isAuthReady = useAuthStore((state) => state.hasHydrated && state.isAuthenticated);
  return useQuery({ queryKey: groupsKey(), queryFn: teamApi.listGroups, staleTime: 30_000, enabled: isAuthReady });
}

export function useCreateGroup() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (payload: { name: string; description?: string }) => teamApi.createGroup(payload),
    onSuccess: () => qc.invalidateQueries({ queryKey: groupsKey() }),
  });
}

export function useUpdateGroup() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ groupId, patch }: { groupId: number; patch: { name?: string; description?: string } }) =>
      teamApi.updateGroup(groupId, patch),
    onSuccess: () => qc.invalidateQueries({ queryKey: groupsKey() }),
  });
}

export function useDeleteGroup() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (groupId: number) => teamApi.deleteGroup(groupId),
    onSuccess: () => qc.invalidateQueries({ queryKey: groupsKey() }),
  });
}

export function useAddGroupMember() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ groupId, userId }: { groupId: number; userId: number }) =>
      teamApi.addGroupMember(groupId, userId),
    onSuccess: () => qc.invalidateQueries({ queryKey: groupsKey() }),
  });
}

export function useRemoveGroupMember() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ groupId, userId }: { groupId: number; userId: number }) =>
      teamApi.removeGroupMember(groupId, userId),
    onSuccess: () => qc.invalidateQueries({ queryKey: groupsKey() }),
  });
}
