@php use App\Constants\CurrencyRole; @endphp
<script>
    'use strict';

    let sendMoneyInfo = {};
    let inputValues = {
        recipient: null,
        walletId: null,
        amount: 0,
    };

    const selectors = {
        walletSelect: '.wallet-select',
        walletInfo: '.wallet-info',
        recipientInfo: '.recipient-info',
        sendAmountInfo: '.send-amount-info',
        summaryAmount: '.summary-amount',
        summaryCharge: '.summary-charge',
        summaryTotal: '.summary-total',
        summaryRate: '.summary-rate',
        recipientWalletAdded: '.recipient-wallet-added',
        myWalletDecreased: '.my-wallet-decreased',
    };

    // Reset data when the recipient changes
    const resetDataOnRecipientChange = () => {
        sendMoneyInfo = {};
        inputValues.walletId = null;
        $(selectors.walletSelect).html('<option disabled selected>{{ __("Select Wallet") }}</option>');
        $(selectors.walletInfo).text('');
        $(selectors.recipientInfo).text('').removeClass('text-danger text-success');
        updateSummary();
    };

    // Update the transaction summary
    const updateSummary = () => {
        const {amount} = inputValues;
        const {fee, fee_type, currency_rate, wallet_currency, min_limit, max_limit} = sendMoneyInfo;

        if (!currency_rate || !wallet_currency || !amount) return;

        if (amount < min_limit || amount > max_limit) {
            $(selectors.sendAmountInfo)
                .text(`{{ __("Amount must be between") }} ${min_limit} {{ siteCurrency() }} {{ __("and") }} ${max_limit} {{ siteCurrency() }}`)
                .addClass('text-danger').removeClass('text-success');
            return;
        } else {
            $(selectors.sendAmountInfo)
                .text(`Min: ${min_limit} {{ siteCurrency() }} | Max: ${max_limit} {{ siteCurrency() }}`)
                .removeClass('text-danger');
        }

        const feeAmount = fee_type === 'fixed' ? parseFloat(fee) : (parseFloat(fee) / 100) * amount;
        const total = parseFloat(amount) + feeAmount;
        const convertedAmount = (total * currency_rate).toFixed(2);
        const recipientAmount = (amount * currency_rate).toFixed(2);

        // Update summary UI
        $(selectors.summaryAmount).text(`${amount.toFixed(2)} {{ siteCurrency() }}`);
        $(selectors.summaryCharge).text(`${feeAmount.toFixed(2)} {{ siteCurrency() }}`);
        $(selectors.summaryTotal).text(`${total.toFixed(2)} {{ siteCurrency() }}`);
        $(selectors.summaryRate).text(`1 {{ siteCurrency() }} = ${currency_rate} ${wallet_currency}`);
        $(selectors.recipientWalletAdded).text(`${recipientAmount} ${wallet_currency}`);
        $(selectors.myWalletDecreased).text(`${convertedAmount} ${wallet_currency}`);
    };

    // Handle recipient validation
    const fetchRecipientInfo = () => {
        if (!inputValues.recipient) return;

        const url = "{{ route('user.wallet.validate.recipient',  [CurrencyRole::SENDER, ':value']) }}"
            .replace(':value', inputValues.recipient);

        $.get(url, (data) => {

            console.log(data);

            if (data.status === 'success') {
                const {currency_role, wallet_currency, currency_rate, type} = data;

                $(selectors.recipientInfo).text(data.message).removeClass('text-danger').addClass('text-success');
                $(selectors.walletSelect).html(data.available_wallets);

                if (type === 'wallet_uuid') {
                    sendMoneyInfo = {...currency_role, wallet_currency, currency_rate};
                    updateWalletFee(currency_role);
                }
                updateSummary();
            } else {
                handleValidationError(data.message);
            }
        }).fail(() => {
            handleValidationError('{{ __("Unable to validate recipient. Please try again.") }}');
        });
    };

    const handleValidationError = (message) => {
        resetDataOnRecipientChange();
        $(selectors.recipientInfo).text(message).addClass('text-danger').removeClass('text-success');
    };

    // Fetch wallet information
    const fetchWalletInfo = () => {
        if (!inputValues.walletId) return;

        const url = "{{ route('user.wallet.info', [CurrencyRole::SENDER,':walletId']) }}"
            .replace(':walletId', inputValues.walletId);

        $.get(url, (data) => {
            sendMoneyInfo = {...data.data};
            updateWalletFee(data.data);
            updateSummary();
        });
    };

    const updateWalletFee = (walletData) => {
        const feeText = walletData.fee_type === 'fixed'
            ? `${walletData.fee} {{ siteCurrency() }}`
            : `${walletData.fee}%`;

        $(selectors.walletInfo).text(`{{ __('Fee') }}: ${feeText}`);
        $(selectors.sendAmountInfo).text(`Min: ${walletData.min_limit} {{ siteCurrency() }} | Max: ${walletData.max_limit} {{ siteCurrency() }}`);
    };

    // Event listeners
    $(document)
        .on('change', '.recipient-input', function () {
            inputValues.recipient = $(this).val();
            resetDataOnRecipientChange();
            fetchRecipientInfo();
        })
        .on('change', selectors.walletSelect, function () {
            inputValues.walletId = $(this).val();
            fetchWalletInfo();
        })
        .on('keyup', '.amount-input', function () {
            inputValues.amount = parseFloat($(this).val()) || 0;
            updateSummary();
        });
</script>
