package com.tangem.feature.wallet.presentation.wallet.subscribers

import com.tangem.domain.account.status.supplier.SingleAccountStatusListSupplier
import com.tangem.domain.account.status.usecase.GetCryptoCurrencyActionsUseCaseV2
import com.tangem.domain.models.wallet.UserWallet
import com.tangem.domain.tokens.model.TokenActionsState
import com.tangem.feature.wallet.child.wallet.model.intents.WalletClickIntents
import com.tangem.feature.wallet.presentation.wallet.state.WalletStateController
import com.tangem.feature.wallet.presentation.wallet.state.transformers.SetCryptoCurrencyActionsTransformer
import com.tangem.utils.annotations.RemoveWithToggle
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.onEach

@Deprecated("Remove with main toggle [DesignFeatureToggles.isRedesignEnabled]")
@RemoveWithToggle("APP_REDESIGN_ENABLED")
internal class SingleWalletButtonsSubscriber @AssistedInject constructor(
    @Assisted override val userWallet: UserWallet,
    override val singleAccountStatusListSupplier: SingleAccountStatusListSupplier,
    private val stateController: WalletStateController,
    private val clickIntents: WalletClickIntents,
    private val getCryptoCurrencyActionsUseCaseV2: GetCryptoCurrencyActionsUseCaseV2,
) : BasicSingleWalletSubscriber() {

    @OptIn(ExperimentalCoroutinesApi::class)
    override fun create(coroutineScope: CoroutineScope): Flow<TokenActionsState> {
        return getPrimaryCurrencyStatusFlow()
            .flatMapLatest {
                getCryptoCurrencyActionsUseCaseV2(accountId = accountId, currency = it.currency)
            }
            .onEach {
                updateContent(tokenActionsState = it)
            }
    }

    private fun updateContent(tokenActionsState: TokenActionsState) {
        stateController.update(
            SetCryptoCurrencyActionsTransformer(
                tokenActionsState = tokenActionsState,
                userWallet = userWallet,
                clickIntents = clickIntents,
                accountId = accountId,
            ),
        )
    }

    @AssistedFactory
    interface Factory {
        fun create(userWallet: UserWallet): SingleWalletButtonsSubscriber
    }
}