import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";

import {
  activateUser,
  approveUser,
  deactivateUser,
  deleteUser,
  getAllExternalUsers,
  getPendingUsers,
} from "../services/api/userService";

// 📦 Query Key
const queryKeys = {
  pendingUsers: ["external-users", "pending"],
  allExternalUsers: ["external-users", "all"],
};

export enum userTypeEnum {
  external = "external_organization",
  individual = "individual",
  externalUsers = "external_organization,individual",
}

export interface ExternalQueryParams {
  orderBy?: string;
  take?: number;
  skip?: number;
  order?: string;
  userType?: userTypeEnum;
  name?: string;
  email?: string;
  username?: string;
  phoneNumber?: string;
}

// ✅ Hook: Get pending external users
export const usePendingExternalUsers = (params?: ExternalQueryParams) => {
  return useQuery({
    queryKey: queryKeys.pendingUsers,
    queryFn: async () => {
      const users = await getPendingUsers(params);
      return users.data;
    },
  });
};

// ✅ Hook: Get all external users
export const useAllExternalUsers = (params?: ExternalQueryParams) => {
  return useQuery({
    queryKey: [...queryKeys.allExternalUsers, params],
    queryFn: async () => {
      const users = await getAllExternalUsers(params);
      return users.data;
    },
  });
};

// ✅ Mutation: Activate user
export const useActivateExternalUser = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => activateUser(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.pendingUsers });
      queryClient.invalidateQueries({ queryKey: queryKeys.allExternalUsers });
    },
  });
};

// Mutatae Approve user
export const useApproveExternalUser = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, status }: { id: string; status: string }) =>
      approveUser(id, status),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.pendingUsers });
      queryClient.invalidateQueries({ queryKey: queryKeys.allExternalUsers });
    },
  });
};


// ✅ Mutation: Deactivate user
export const useDeactivateExternalUser = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => deactivateUser(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.pendingUsers });
      queryClient.invalidateQueries({ queryKey: queryKeys.allExternalUsers });
    },
  });
};

// ✅ Mutation: Delete user
export const useDeleteExternalUser = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => deleteUser(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.pendingUsers });
      queryClient.invalidateQueries({ queryKey: queryKeys.allExternalUsers });
    },
  });
};
