import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";
import { apiGet } from "../../../../lib/api/methods";
import { ADMIN_TRANSACTIONS_ENDPOINTS } from "./endpoints";
import { AdminTransaction } from "./useTransactionsFetch";
import { PaginationController } from "../../../useAppPagination";
import { convertDateStringToDate } from "../../../../utils/helper";
import { TransactionStatus } from "../../../../components/table/features/transactions/types/transaction";

export type UserTransactionHistory = {
  id: string;
  title: string;
  amount: number;
  credits: number;
  status: TransactionStatus;
  createdAt: string;
};

type UserTransactionResponse = {
  user: {
    uuid: string;
    name: string;
    email: string;
    walletBalance: number;
    profilePicture: string;
    createdAt: string;
  };
  summary: {
    totalTransactions: number;
    successfulTransactions: number;
    failedTransactions: number;
    totalSpent: number;
  };
  transactions: Array<AdminTransaction>;
};

export default function useUserTransactionsFetch(
  pagination: PaginationController,
) {
  const { userId } = useParams<{ userId: string }>();

  const { data, isPending, isError, error } = useQuery({
    queryKey: [
      "user-transactions",
      userId,
      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<UserTransactionResponse>(
        ADMIN_TRANSACTIONS_ENDPOINTS.GET_USER_TRANSACTIONS(userId),
        queryParams,
      );

      const transactionsData: UserTransactionHistory[] =
        res.data.transactions.map((transaction) => {
          return {
            id: transaction.uuid,
            title: transaction.packageName,
            amount: transaction.amount,
            credits: transaction.credits,
            status: transaction.status as TransactionStatus,
            createdAt: convertDateStringToDate(transaction.createdAt),
          };
        });

      return {
        user: res.data.user,
        summary: res.data.summary,
        transactions: transactionsData,
        pagination: res.meta,
      };
    },
    staleTime: 60 * 1000,
    placeholderData: keepPreviousData,
    enabled: !!userId,
  });

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