import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { apiGet } from "../../../../lib/api/methods";
import { ADMIN_USERS } from "./endpoints";
import { PaginationController } from "../../../useAppPagination";

export type AdminUser = {
  uuid: string;
  name?: string;
  firstName: string;
  lastName: string;
  email: string;
  isActive: boolean;
  emailVerified: boolean;
  roles: string[];
  createdAt: string;

  totalSpent?: string;
  walletBalance?: string;
  mobileNumber?: string;
  profilePicture?: string;
  dialCode?: string;
};

type AdminUsersResponse = Array<AdminUser>;

export default function useUsersFetch(pagination: PaginationController) {
  const { data, isPending, isError, error } = useQuery({
    queryKey: [
      "users",
      pagination.params.page,
      pagination.params.limit,
      pagination.params.searchQuery,
      pagination.params.sortBy,
      pagination.params.sortDirection,
    ],
    queryFn: async () => {
      const queryParams = {
        limit: pagination.params.limit,
        page: pagination.params.page,
        search: pagination.params.searchQuery,
        sortBy: pagination.params.sortBy,
        sortOrder: pagination?.params?.sortDirection?.toUpperCase(),
      };

      const res = await apiGet<AdminUsersResponse>(
        ADMIN_USERS.GET_USERS,
        queryParams,
      );
      return {
        users: res.data.map((user) => ({
          ...user,
          name: `${user.firstName} ${user.lastName}`,

          creditBalance: user.walletBalance ?? "100",
          totalSpent: user.totalSpent ?? "$10",
          phoneNumber: `${user.dialCode || ""} ${user.mobileNumber || "N/A"}`,
        })),
        pagination: res.meta,
      };
    },

    staleTime: 60 * 1000,
    placeholderData: keepPreviousData,
    retry: false,
  });

  return {
    data: data,
    loading: isPending,
    error,
    isError,
  };
}
