"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"

import type { Transactions } from "@/types/components/myPages/myPage/earnAndBurn"

export default function TransactionTable({
  initialJourneyTransactions,
}: {
  initialJourneyTransactions: {
    data: { transactions: Transactions }
    meta: { totalPages: number }
  }
}) {
  const limit = 5
  const [page, setPage] = useState(1)
  const { data, isFetching, isLoading } =
    trpc.user.transaction.friendTransactions.useQuery(
      {
        limit,
        page,
      },
      {
        // TODO: fix the initial data issues on page load
        // initialData: initialJourneyTransactions,
        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}
    </>
  )
}
