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

export type AdminTransaction = {
  uuid: string;
  userUuid: string;
  userName: string;
  profilePicture: string;
  email: string;
  packageName: string;
  amount: number;
  currency: string;
  provider: string;
  credits: number;
  gatewayTransactionId: string | null;
  gatewayPaymentId: string | null;
  failureReason: string | null;
  status: string;
  createdAt: string;
};

type AdminTransactionListResponse = Array<AdminTransaction>;

export default function useAdminTransactionsFetch(
  pagination: PaginationController,
) {
  const { data, isPending, isError, error } = useQuery({
    queryKey: [
      "transactions",
      pagination.params.page,
      pagination.params.limit,
      pagination.params.searchQuery,
      pagination.params.sortBy,
      pagination.params.sortDirection,
    ],
    retry: false,
    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<AdminTransactionListResponse>(
        ADMIN_TRANSACTIONS_ENDPOINTS.GET_ADMIN_TRANSACTIONS,
        queryParams,
      );

      const transactionsData: Transaction[] = res.data.map((transaction) => {
        return {
          id: transaction.uuid,
          userId: transaction.userUuid,
          name: transaction.userName,
          date: convertDateStringToDate(transaction.createdAt),
          profilePicture: transaction.profilePicture,
          email: transaction.email,
          title: transaction.packageName,
          amount: transaction.amount,
          credits: transaction.credits,
          status: transaction.status as TransactionStatus,
        };
      });

      return {
        data: transactionsData,
        meta: res.meta,
      };
    },
    staleTime: 60 * 1000,
    placeholderData: keepPreviousData,
  });

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