"use client"

import { useRef, useState } from "react"

import { RewardIcon } from "@/components/Blocks/DynamicContent/Rewards/RewardIcon"
import Pagination from "@/components/MyPages/Pagination"
import Grids from "@/components/TempDesignSystem/Grids"
import Title from "@/components/TempDesignSystem/Text/Title"

import Redeem from "../Redeem"

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

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

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

  const totalPages = Math.ceil(rewards.length / pageSize)
  const startIndex = (currentPage - 1) * pageSize
  const endIndex = startIndex + pageSize
  const currentRewards = 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>
        {currentRewards.map((reward, idx) => (
          <article className={styles.card} key={`${reward.reward_id}-${idx}`}>
            <div className={styles.content}>
              <RewardIcon rewardId={reward.reward_id} />
              <Title
                as="h4"
                level="h3"
                textAlign="center"
                textTransform="regular"
              >
                {reward.label}
              </Title>
            </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>
  )
}
