"use client"

import { useRef, useState } from "react"

import { REWARDS_PER_PAGE } from "@/constants/rewards"
import { trpc } from "@/lib/trpc/client"

import { RewardIcon } from "@/components/Blocks/DynamicContent/Rewards/RewardIcon"
import ScriptedRewardText from "@/components/Blocks/DynamicContent/Rewards/ScriptedRewardText"
import Pagination from "@/components/MyPages/Pagination"
import ExpirationDate from "@/components/Rewards/ExpirationDate"
import Grids from "@/components/TempDesignSystem/Grids"
import Title from "@/components/TempDesignSystem/Text/Title"
import useLang from "@/hooks/useLang"
import { getEarliestExpirationDate } from "@/utils/rewards"

import Redeem from "../Redeem"

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

import type { CurrentRewardsClientProps } from "@/types/components/myPages/myPage/accountPage"
import type { Reward } from "@/types/components/myPages/rewards"

export default function ClientCurrentRewards({
  rewards: initialData,
  showRedeem,
  membershipNumber,
}: CurrentRewardsClientProps) {
  const lang = useLang()
  const containerRef = useRef<HTMLDivElement>(null)
  const [currentPage, setCurrentPage] = useState(1)

  const { data } = trpc.contentstack.rewards.current.useQuery<{
    rewards: Reward[]
  }>(
    {
      lang,
    },
    {
      initialData: { rewards: initialData },
    }
  )

  if (!data) {
    return null
  }

  const rewards = data.rewards

  const totalPages = Math.ceil(rewards.length / REWARDS_PER_PAGE)
  const startIndex = (currentPage - 1) * REWARDS_PER_PAGE
  const endIndex = startIndex + REWARDS_PER_PAGE
  const paginatedRewards = rewards.slice(startIndex, endIndex)

  function handlePageChange(page: number) {
    requestAnimationFrame(() => {
      setCurrentPage(page)
      containerRef.current?.scrollIntoView({
        behavior: "smooth",
        block: "start",
        inline: "nearest",
      })
    })
  }

  return (
    <div ref={containerRef} className={styles.container}>
      <Grids.Stackable>
        {paginatedRewards.map((reward, idx) => {
          const earliestExpirationDate = getEarliestExpirationDate(reward)

          return (
            <article className={styles.card} key={`${reward.reward_id}-${idx}`}>
              <div className={styles.content}>
                <RewardIcon rewardId={reward.reward_id} />
                {showRedeem && <ScriptedRewardText reward={reward} />}
                <Title
                  as="h4"
                  level="h3"
                  textAlign="center"
                  textTransform="regular"
                >
                  {reward.label}
                </Title>
                {earliestExpirationDate ? (
                  <ExpirationDate expirationDate={earliestExpirationDate} />
                ) : null}
              </div>
              {showRedeem && "redeem_description" in reward && (
                <div className={styles.btnContainer}>
                  <Redeem reward={reward} membershipNumber={membershipNumber} />
                </div>
              )}
            </article>
          )
        })}
      </Grids.Stackable>
      {totalPages > 1 && (
        <Pagination
          pageCount={totalPages}
          currentPage={currentPage}
          handlePageChange={handlePageChange}
        />
      )}
    </div>
  )
}
