package com.tangem.feature.wallet.presentation.wallet.state.transformers

import com.tangem.domain.models.wallet.UserWallet
import com.tangem.domain.wallets.usecase.GetWalletIconUseCase
import com.tangem.feature.wallet.child.wallet.model.intents.WalletClickIntents
import com.tangem.feature.wallet.presentation.wallet.domain.WalletImageResolver
import com.tangem.feature.wallet.presentation.wallet.state.model.WalletScreenState
import com.tangem.feature.wallet.presentation.wallet.state.utils.WalletLoadingStateFactory
import kotlinx.collections.immutable.toImmutableList

internal class AddWalletTransformer(
    private val userWallet: UserWallet,
    private val clickIntents: WalletClickIntents,
    private val walletImageResolver: WalletImageResolver,
    private val getWalletIconUseCase: GetWalletIconUseCase,
    private val isAddFundsStage1Enabled: Boolean,
    private val isManageFundsEnabled: Boolean,
) : WalletScreenStateTransformer {

    private val walletLoadingStateFactory by lazy {
        WalletLoadingStateFactory(
            clickIntents = clickIntents,
            walletImageResolver = walletImageResolver,
            getWalletIconUseCase = getWalletIconUseCase,
            isAddFundsStage1Enabled = isAddFundsStage1Enabled,
            isManageFundsEnabled = isManageFundsEnabled,
        )
    }

    override fun transform(prevState: WalletScreenState): WalletScreenState {
        return prevState.copy(
            // Select the newly added wallet synchronously (it is appended to the end), mirroring
            // Initialize/Delete transformers. Otherwise selectedWalletIndex stays stale until the
            // deferred scroll settles, and getSelectedWalletId() returns the previously selected wallet.
            selectedWalletIndex = prevState.wallets2.size,
            wallets = (prevState.wallets + walletLoadingStateFactory.create(userWallet)).toImmutableList(),
            wallets2 = (prevState.wallets2 + walletLoadingStateFactory.create2(userWallet)).toImmutableList(),
        )
    }
}