"use client"

import { trpc } from "@/lib/trpc/client"
import { ApiReward, 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 Surprises from "../Surprises"

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

import type { CurrentRewardsClientProps } from "@/types/components/blocks/currentRewards"

export default function ClientCurrentRewards({
  initialCurrentRewards,
  membershipNumber,
}: 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],
        },
      }
    )

  if (isLoading) {
    return <LoadingSpinner />
  }

  const rewards =
    data?.pages
      .flatMap((page) => page?.rewards)
      .filter((reward): reward is Reward => !!reward) ?? []

  const surprises =
    data?.pages
      .flatMap((page) => page?.apiRewards)
      .filter((reward): reward is ApiReward => reward?.type === "surprise") ??
    []

  if (!rewards.length && !surprises.length) {
    return null
  }

  function loadMoreData() {
    if (hasNextPage) {
      fetchNextPage()
    }
  }

  return (
    <>
      <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} />
        ))}
      <Surprises surprises={surprises} membershipNumber={membershipNumber} />
    </>
  )
}
