"use client"

import { trpc } from "@/lib/trpc/client"
import { Reward } from "@/server/routers/contentstack/reward/output"

import LoadingSpinner from "@/components/LoadingSpinner"
import Grids from "@/components/TempDesignSystem/Grids"
import ShowMoreButton from "@/components/TempDesignSystem/ShowMoreButton"
import Title from "@/components/TempDesignSystem/Text/Title"
import useLang from "@/hooks/useLang"

import styles from "./current.module.css"

type CurrentRewardsClientProps = {
  initialCurrentRewards: { rewards: Reward[]; nextCursor: number | undefined }
}
export default function ClientCurrentRewards({
  initialCurrentRewards,
}: CurrentRewardsClientProps) {
  const lang = useLang()
  const { data, isFetching, fetchNextPage, hasNextPage, isLoading } =
    trpc.contentstack.rewards.current.useInfiniteQuery(
      {
        limit: 3,
        lang,
      },
      {
        getNextPageParam: (lastPage) => lastPage?.nextCursor,
        initialData: {
          pageParams: [undefined, 1],
          pages: [initialCurrentRewards],
        },
      }
    )
  function loadMoreData() {
    if (hasNextPage) {
      fetchNextPage()
    }
  }
  const filteredRewards =
    data?.pages.filter((page) => page && page.rewards) ?? []
  const rewards = filteredRewards.flatMap((page) => page?.rewards) as Reward[]

  if (isLoading) {
    return <LoadingSpinner />
  }

  if (!rewards.length) {
    return null
  }

  return (
    <div>
      <Grids.Stackable>
        {rewards.map((reward, idx) => (
          <article className={styles.card} key={`${reward.reward_id}-${idx}`}>
            <Title
              as="h4"
              level="h3"
              textAlign="center"
              textTransform="regular"
            >
              {reward.label}
            </Title>
          </article>
        ))}
      </Grids.Stackable>
      {hasNextPage &&
        (isFetching ? (
          <LoadingSpinner />
        ) : (
          <ShowMoreButton loadMoreData={loadMoreData} />
        ))}
    </div>
  )
}
