'use client'
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useRef, useState, useEffect, useMemo } from 'react';
import { Formik, Form, Field } from 'formik';
import { useTranslation } from 'react-i18next';
import { object, string } from 'yup';
import '../../context/DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import '../../context/ViewContext/ViewContext.js';
import '../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../utils/constants/colors.js';
import '../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import '../../shared/consts/index.js';
import '../../events/dynamicEvents.js';
import '../../../../_virtual/_tslib.js';
import '../../context/CaptchaContext/CaptchaContext.js';
import '../../context/ErrorContext/ErrorContext.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import { getOrdinalNumber } from '../../utils/functions/getOrdinalNumber/getOrdinalNumber.js';
import '../../store/state/nonce/nonce.js';
import '@dynamic-labs-sdk/client/core';
import '../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../config/ApiEndpoint.js';
import '@dynamic-labs/locale';
import '../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../store/state/primaryWalletId/primaryWalletId.js';
import '../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../context/AccountExistsContext/AccountExistsContext.js';
import '../../context/UserWalletsContext/UserWalletsContext.js';
import '../../store/state/authMode/authMode.js';
import '../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../utils/functions/compareChains/compareChains.js';
import '../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../context/ThemeContext/ThemeContext.js';
import '../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../context/LoadingContext/LoadingContext.js';
import '../../context/WalletContext/WalletContext.js';
import '../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import '../../context/MockContext/MockContext.js';
import '../../views/CollectUserDataView/useFields.js';
import '../../context/FieldsStateContext/FieldsStateContext.js';
import '../../context/UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import '../../store/state/walletOptions/walletOptions.js';
import '../Accordion/components/AccordionItem/AccordionItem.js';
import '../Alert/Alert.js';
import { Typography } from '../Typography/Typography.js';
import '../ShadowDOM/ShadowDOM.js';
import { TypographyButton } from '../TypographyButton/TypographyButton.js';
import { FormFieldLabel } from '../FormFieldLabel/FormFieldLabel.js';
import '../IconButton/IconButton.js';
import '../InlineWidget/InlineWidget.js';
import { Input } from '../Input/Input.js';
import '../IsBrowser/IsBrowser.js';
import '../MenuList/Dropdown/Dropdown.js';
import '../OverlayCard/OverlayCard.js';
import '../Transition/ZoomTransition/ZoomTransition.js';
import '../Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../Transition/OpacityTransition/OpacityTransition.js';
import '../PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../Popper/Popper/Popper.js';
import '../Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import '../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../../context/WalletGroupContext/WalletGroupContext.js';
import '../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../context/FooterAnimationContext/index.js';
import '../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../context/PasskeyContext/PasskeyContext.js';
import '../../context/OnrampContext/OnrampContext.js';
import { useSendBalanceState, setSendBalanceVariable } from '../../store/state/sendBalances.js';
import { TokensBalanceDropdown } from '../SendBalancePageLayout/components/TokensBalanceDropdown/TokensBalanceDropdown.js';
import { getDisplayFiatPrice } from '../TransactionConfirmationPageLayout/utils.js';
import '../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../index.js';
import '../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../store/state/tokenBalances.js';
import '../../store/state/multichainBalances.js';
import '../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';

const sendBalanceFormInitialValues = {
    amount: '',
    recipient: '',
};
const getDisplayErrorMessage = (errors, t, field, decimals) => {
    const mapFieldAndErrorToMessage = {
        amount: {
            invalidDecimals: t('dyn_send_transaction.validation.amount.invalid_decimals', { decimals }),
            invalidFormat: t('dyn_send_transaction.validation.amount.invalid_decimals', { decimals }),
            overBalance: t('dyn_send_transaction.validation.amount.over_balance'),
            required: t('dyn_send_transaction.validation.amount.required'),
        },
        recipient: {
            invalidFormat: t('dyn_send_transaction.validation.recipient.invalid_format'),
            required: t('dyn_send_transaction.validation.recipient.required'),
        },
    };
    const errorType = errors[field];
    if (errorType) {
        const errorMessage = mapFieldAndErrorToMessage[field][errorType];
        return errorMessage.replace('{decimals}', getOrdinalNumber(decimals !== null && decimals !== void 0 ? decimals : 0));
    }
    return '';
};
const SendBalanceForm = ({ initialValues, onSubmit, decimals = 18, validateAddress = () => true, validateAmount = () => true, currentToken, transaction, tokenBalances, setCurrentToken, isLoading, }) => {
    const { t } = useTranslation();
    const { showFiat } = useInternalDynamicContext();
    const floatingValueRef = useRef(null);
    const [leftSymbolPadding, setLeftSymbolPadding] = useState(0);
    const { amount } = useSendBalanceState();
    useEffect(() => {
        if (floatingValueRef.current) {
            const floatingDivWidth = floatingValueRef.current.offsetWidth;
            setLeftSymbolPadding(floatingDivWidth + 15);
        }
    }, [currentToken]);
    const sendBalanceFormValidationSchema = useMemo(() => {
        const decimalsRegex = new RegExp(`^\\d*(\\.\\d{1,${decimals}})?$`);
        return object().shape({
            amount: string()
                .required('required')
                .matches(/^\d*(\.\d+)?$/, 'invalidFormat')
                .matches(decimalsRegex, 'invalidDecimals')
                .test({
                message: 'overBalance',
                test: (value) => validateAmount(value),
            }),
            recipient: string()
                .required('required')
                .test({
                message: 'invalidFormat',
                test: (value) => validateAddress(value),
            }),
        });
    }, [decimals, validateAddress, validateAmount]);
    return (jsx(Formik, { initialValues: initialValues || sendBalanceFormInitialValues, validationSchema: sendBalanceFormValidationSchema, onSubmit: (values) => onSubmit(values), validateOnChange: false, validateOnBlur: false, children: ({ errors, touched, values, handleChange, setFieldValue, setErrors, handleBlur, setFieldTouched, validateField, }) => {
            var _a;
            return (jsxs(Form, { className: 'send-balance-form', children: [jsxs("div", { className: 'send-balance-page-layout__balance-container', children: [jsx(FormFieldLabel, { children: "Select any token" }), jsx(TokensBalanceDropdown, { tokenBalances: tokenBalances !== null && tokenBalances !== void 0 ? tokenBalances : (currentToken && [currentToken]), currentToken: currentToken, setCurrentToken: setCurrentToken, isLoading: isLoading, setFieldValue: setFieldValue, setErrors: setErrors })] }), jsxs("div", { className: 'send-balance-form__amount-container', children: [jsx(Field, { variant: 'regular', className: `send-balance-form__amount-container__field ${showFiat ? 'fiat' : ''}`, name: 'amount', id: 'amount', onChange: (e) => {
                                    const newValue = e.target.value;
                                    // Matching 123, 123.45, .45, 123.
                                    if (newValue !== '' && !/^(?:\d+|\d*\.\d*|)$/.test(newValue)) {
                                        return;
                                    }
                                    setErrors({});
                                    handleChange(e);
                                    if (!newValue || Number.isNaN(newValue)) {
                                        setSendBalanceVariable('amount', 0);
                                        return;
                                    }
                                    setSendBalanceVariable('amount', (currentToken === null || currentToken === void 0 ? void 0 : currentToken.price) ? Number(newValue) : undefined);
                                }, onBlur: (e) => {
                                    handleBlur(e);
                                    setFieldTouched('amount', true);
                                    validateField('amount');
                                }, placeholder: t('dyn_send_transaction.data.amount.placeholder'), as: Input, error: errors['amount'], copykey: 'dyn_send_transaction.data.amount.label', message: touched['amount'] &&
                                    getDisplayErrorMessage(errors, t, 'amount', decimals), style: {
                                    paddingLeft: `${leftSymbolPadding}px`,
                                } }), jsx("div", { className: 'send-balance-form__amount-container__floating_value', ref: floatingValueRef, children: jsx(Typography, { variant: 'title', weight: 'regular', color: 'secondary', children: currentToken === null || currentToken === void 0 ? void 0 : currentToken.symbol }) }), jsx("div", { className: 'send-balance-form__amount-container__balance', children: showFiat && !Number.isNaN(amount) && (jsxs(Fragment, { children: [jsx(Typography, { variant: 'body_mini', weight: 'bold', color: 'secondary', children: "$" }), jsx(Typography, { variant: 'body_mini', weight: 'regular', color: 'secondary', children: getDisplayFiatPrice(amount, currentToken) })] })) })] }), jsx(Typography, { className: 'send-balance-form__amount_available', variant: 'body_small', weight: 'regular', color: 'secondary', as: 'div', children: jsxs("div", { style: { display: 'flex', gap: '0.225rem' }, children: [jsx(Typography, { className: 'send-balance-form__amount_available__line', variant: 'body_small', weight: 'bold', color: 'primary', as: 'div', children: (_a = currentToken === null || currentToken === void 0 ? void 0 : currentToken.balance) !== null && _a !== void 0 ? _a : 0 }), `${currentToken === null || currentToken === void 0 ? void 0 : currentToken.symbol} Available`] }) }), jsx(Typography, { variant: 'body_small', weight: 'regular', color: 'secondary', copykey: 'dyn_send_transaction.data.recipient.label', children: "Recipient Address" }), jsx(Field, { className: 'send-balance-form__field', placeholder: t('dyn_send_transaction.data.recipient.placeholder'), label: t('dyn_send_transaction.data.recipient.label'), id: 'recipient', name: 'recipient', as: Input, error: errors['recipient'], copykey: 'dyn_send_transaction.data.recipient.label', message: touched['recipient'] &&
                            getDisplayErrorMessage(errors, t, 'recipient') }), jsx(TypographyButton, { dataTestId: 'sendBalanceFormSubmitButton', expanded: true, type: 'submit', buttonVariant: 'primary', buttonPadding: 'small', buttonClassName: 'send-balance-form__button', copykey: 'dyn_send_transaction.preview_transaction', children: t('dyn_send_transaction.preview_transaction') })] }));
        } }));
};

export { SendBalanceForm };
