"use client"

import { keepPreviousData } from "@tanstack/react-query"
import { useState } from "react"

import { trpc } from "@/lib/trpc/client"

import LoadingSpinner from "@/components/LoadingSpinner"
import Pagination from "@/components/MyPages/Pagination"

import ClientTable from "./ClientTable"

export default function TransactionTable() {
  const limit = 5
  const [page, setPage] = useState(1)
  const { data, isFetching, isLoading } =
    trpc.user.transaction.friendTransactions.useQuery(
      {
        limit,
        page,
      },
      {
        placeholderData: keepPreviousData,
      }
    )

  return isLoading ? (
    <LoadingSpinner />
  ) : (
    <>
      <ClientTable transactions={data?.data.transactions || []} />
      {data && data.meta.totalPages > 1 ? (
        <Pagination
          handlePageChange={setPage}
          pageCount={data.meta.totalPages}
          isFetching={isFetching}
          currentPage={page}
        />
      ) : null}
    </>
  )
}
