import clsx from 'clsx' import _ from 'lodash' import { useUser } from '../hooks/use-user' import { formatMoney } from '../../common/util/format' import { Col } from './layout/col' import { Row } from './layout/row' import { useUserContractBets } from '../hooks/use-user-bets' import { MAX_LOAN_PER_CONTRACT } from '../../common/bet' import { InfoTooltip } from './info-tooltip' import { Spacer } from './layout/spacer' export function AmountInput(props: { amount: number | undefined onChange: (newAmount: number | undefined) => void error: string | undefined setError: (error: string | undefined) => void contractIdForLoan: string | undefined minimumAmount?: number disabled?: boolean className?: string inputClassName?: string // Needed to focus the amount input inputRef?: React.MutableRefObject }) { const { amount, onChange, error, setError, contractIdForLoan, disabled, className, inputClassName, minimumAmount, inputRef, } = props const user = useUser() const userBets = useUserContractBets(user?.id, contractIdForLoan) ?? [] const openUserBets = userBets.filter((bet) => !bet.isSold && !bet.sale) const prevLoanAmount = _.sumBy(openUserBets, (bet) => bet.loanAmount ?? 0) const loanAmount = contractIdForLoan ? Math.min(amount ?? 0, MAX_LOAN_PER_CONTRACT - prevLoanAmount) : 0 const onAmountChange = (str: string) => { if (str.includes('-')) { onChange(undefined) return } const amount = parseInt(str.replace(/[^\d]/, '')) if (str && isNaN(amount)) return if (amount >= 10 ** 9) return onChange(str ? amount : undefined) const loanAmount = contractIdForLoan ? Math.min(amount, MAX_LOAN_PER_CONTRACT - prevLoanAmount) : 0 const amountNetLoan = amount - loanAmount if (user && user.balance < amountNetLoan) { setError('Insufficient balance') } else if (minimumAmount && amount < minimumAmount) { setError('Minimum amount: ' + formatMoney(minimumAmount)) } else { setError(undefined) } } const amountNetLoan = (amount ?? 0) - loanAmount const remainingBalance = Math.max(0, (user?.balance ?? 0) - amountNetLoan) return ( {error && (
{error}
)} {user && ( {contractIdForLoan && ( Amount loaned{' '} {formatMoney(loanAmount)}{' '} )} Remaining balance{' '} {formatMoney(Math.floor(remainingBalance))} )} ) }