import React, { useEffect, useMemo, useState } from 'react'; import { Modal, Button } from '@akinon/next/components'; import { RewardSelectionModalProps } from '../types/custom-render.types'; import type { RewardItem, RewardCategory } from '../types/payment.types'; import { parseRewardAmount, getCappedRewardAmounts } from '../utils/reward-utils'; const formatAmount = (amount: number | string, currency?: string) => { const formatted = parseRewardAmount(amount).toFixed(2); return currency ? `${formatted} ${currency.toUpperCase()}` : formatted; }; const isSameReward = (a: RewardItem, b: RewardItem) => a.type === b.type; const RewardSelectionModal: React.FC = ({ open, onClose, onConfirm, rewards, selectedRewards, isLoading = false, currency, payableAmount, texts }) => { const [draft, setDraft] = useState(selectedRewards); useEffect(() => { if (open) { setDraft(selectedRewards); } }, [open, selectedRewards]); const cappedAmounts = useMemo( () => getCappedRewardAmounts(draft, payableAmount), [draft, payableAmount] ); const grouped = useMemo(() => { const map: Record = { special: [], general: [] }; rewards.forEach((reward) => { if (map[reward.type]) { map[reward.type].push(reward); } }); return map; }, [rewards]); const toggleReward = (reward: RewardItem) => { setDraft((current) => { const exists = current.some((item) => isSameReward(item, reward)); if (exists) { return current.filter((item) => !isSameReward(item, reward)); } const withoutSameType = current.filter( (item) => item.type !== reward.type ); return [...withoutSameType, reward]; }); }; const isSelected = (reward: RewardItem) => draft.some((item) => isSameReward(item, reward)); const categoryLabel = (category: RewardCategory) => category === 'special' ? texts.rewardCategorySpecialText : texts.rewardCategoryGeneralText; const handleConfirm = async () => { await onConfirm(draft); }; const hasRewards = rewards.length > 0; return (
{texts.rewardModalDescription && (

{texts.rewardModalDescription}

)} {!hasRewards ? (

{texts.rewardModalEmptyMessage}

) : (
{(Object.keys(grouped) as RewardCategory[]) .filter((category) => grouped[category].length > 0) .map((category) => (

{categoryLabel(category)}

    {grouped[category].map((reward) => { const selected = isSelected(reward); const fullValue = parseRewardAmount(reward.amount); const capped = cappedAmounts[reward.type]; const isCapped = selected && capped < fullValue; return (
  • ); })}
))}
)}
); }; export default RewardSelectionModal;