package com.tangem.features.createwalletselection

import com.tangem.common.TangemBlogUrlBuilder
import com.tangem.common.routing.AppRoute
import com.tangem.core.analytics.api.AnalyticsEventHandler
import com.tangem.core.analytics.models.AnalyticsParam
import com.tangem.core.analytics.models.Basic
import com.tangem.core.analytics.models.event.OnboardingAnalyticsEvent
import com.tangem.core.analytics.utils.TrackingContextProxy
import com.tangem.core.decompose.di.ModelScoped
import com.tangem.core.decompose.model.Model
import com.tangem.core.decompose.navigation.Router
import com.tangem.core.decompose.ui.UiMessageSender
import com.tangem.core.navigation.url.UrlOpener
import com.tangem.core.ui.components.label.entity.LabelStyle
import com.tangem.core.ui.components.label.entity.LabelUM
import com.tangem.core.ui.extensions.resourceReference
import com.tangem.core.ui.message.dialog.Dialogs.hotWalletCreationNotSupportedDialog
import com.tangem.domain.hotwallet.IsHotWalletCreationSupported
import com.tangem.domain.wallets.usecase.GenerateBuyTangemCardLinkUseCase
import com.tangem.features.createwalletselection.entity.CreateWalletSelectionUM
import com.tangem.features.createwalletselection.impl.R
import com.tangem.utils.coroutines.CoroutineDispatcherProvider
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

@Suppress("LongParameterList")
@ModelScoped
internal class CreateWalletSelectionModel @Inject constructor(
    override val dispatchers: CoroutineDispatcherProvider,
    private val router: Router,
    private val trackingContextProxy: TrackingContextProxy,
    private val analyticsEventHandler: AnalyticsEventHandler,
    private val generateBuyTangemCardLinkUseCase: GenerateBuyTangemCardLinkUseCase,
    private val urlOpener: UrlOpener,
    private val isHotWalletCreationSupported: IsHotWalletCreationSupported,
    private val uiMessageSender: UiMessageSender,
) : Model() {

    internal val uiState: StateFlow<CreateWalletSelectionUM>
        field = MutableStateFlow(
            CreateWalletSelectionUM(
                onBackClick = { router.pop() },
                blocks = persistentListOf(
                    CreateWalletSelectionUM.Block(
                        title = resourceReference(R.string.wallet_create_hardware_title),
                        titleLabel = LabelUM(
                            text = resourceReference(R.string.common_recommended),
                            style = LabelStyle.ACCENT,
                        ),
                        description = resourceReference(R.string.wallet_add_hardware_description),
                        onClick = ::onHardwareWalletClick,
                    ),
                    CreateWalletSelectionUM.Block(
                        title = resourceReference(R.string.wallet_create_mobile_title),
                        titleLabel = null,
                        description = resourceReference(R.string.wallet_add_mobile_description),
                        onClick = ::onMobileWalletClick,
                    ),
                ),
                onBuyClick = ::onBuyClick,
                shouldShowAlreadyHaveWallet = true,
                onWhatToChooseClick = ::onWhatToChooseClick,
            ),
        )

    init {
        // temporarily disabled by timer and enabled by default
        // showAlreadyHaveWalletWithDelay()
    }

    @Suppress("UnusedPrivateMember")
    private fun showAlreadyHaveWalletWithDelay() {
        modelScope.launch {
            delay(SHOW_ALREADY_HAVE_WALLET_DELAY)
            uiState.update { it.copy(shouldShowAlreadyHaveWallet = true) }
        }
    }

    private fun onMobileWalletClick() {
        trackingContextProxy.addHotWalletContext()
        analyticsEventHandler.send(
            event = OnboardingAnalyticsEvent.Onboarding.ButtonMobileWallet(
                source = AnalyticsParam.ScreensSources.AddNewWallet.value,
            ),
        )
        if (!isHotWalletCreationSupported()) {
            uiMessageSender.send(
                hotWalletCreationNotSupportedDialog(isHotWalletCreationSupported.getLeastVersionName()),
            )
            return
        }

        router.push(AppRoute.CreateMobileWallet(AnalyticsParam.ScreensSources.AddNewWallet))
    }

    private fun onHardwareWalletClick() {
        router.push(AppRoute.CreateHardwareWallet(source = AnalyticsParam.ScreensSources.AddNew))
    }

    private fun onBuyClick() {
        analyticsEventHandler.send(Basic.ButtonBuy(source = AnalyticsParam.ScreensSources.AddNewWallet))
        modelScope.launch {
            generateBuyTangemCardLinkUseCase
                .invoke(GenerateBuyTangemCardLinkUseCase.Source.Creation).let { urlOpener.openUrl(it) }
        }
    }

    private fun onWhatToChooseClick() {
        modelScope.launch {
            urlOpener.openUrl(TangemBlogUrlBuilder.build(TangemBlogUrlBuilder.Post.WhatWalletToChoose))
        }
    }

    companion object {
        private const val SHOW_ALREADY_HAVE_WALLET_DELAY = 3000L
    }
}