package com.tangem.feature.tokendetails.presentation.tokendetails.ui.components.express.exchange

import androidx.compose.animation.AnimatedContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.tangem.common.ui.expressStatus.ExpressEstimate
import com.tangem.common.ui.expressStatus.ExpressHideButton
import com.tangem.common.ui.expressStatus.ExpressProvider
import com.tangem.common.ui.expressStatus.ExpressStatusBlock
import com.tangem.common.ui.expressStatus.state.ExpressLinkUM
import com.tangem.common.ui.expressStatus.state.ExpressStatusItemState
import com.tangem.common.ui.expressStatus.state.ExpressStatusItemUM
import com.tangem.common.ui.expressStatus.state.ExpressStatusUM
import com.tangem.core.ui.R
import com.tangem.core.ui.extensions.resourceReference
import com.tangem.core.ui.components.SpacerH
import com.tangem.core.ui.components.SpacerH10
import com.tangem.core.ui.components.SpacerH12
import com.tangem.core.ui.components.SpacerH16
import com.tangem.core.ui.components.SpacerH24
import com.tangem.core.ui.components.notifications.CurrencyNotification
import com.tangem.core.ui.extensions.TextReference
import com.tangem.core.ui.extensions.stringResourceSafe
import com.tangem.core.ui.res.TangemTheme
import com.tangem.feature.swap.domain.models.domain.ExchangeStatus
import com.tangem.feature.swap.domain.models.domain.ExchangeStatus.Companion.isFailed
import com.tangem.feature.tokendetails.presentation.tokendetails.state.components.ExchangeStatusNotification
import com.tangem.feature.tokendetails.presentation.tokendetails.state.express.ExchangeStatusState
import com.tangem.feature.tokendetails.presentation.tokendetails.state.express.ExchangeUM
import kotlinx.collections.immutable.toImmutableList

@Composable
internal fun ExchangeStatusBottomSheetContent(
    state: ExchangeUM,
    isExpressShareButtonEnabled: Boolean,
    extraContent: (@Composable () -> Unit)? = null,
) {
    Column(
        modifier = Modifier
            .padding(horizontal = TangemTheme.dimens.spacing16)
            .verticalScroll(rememberScrollState()),
    ) {
        SpacerH10()
        Text(
            text = stringResourceSafe(id = R.string.express_exchange_status_title),
            style = TangemTheme.typography.subtitle1,
            color = TangemTheme.colors.text.primary1,
            modifier = Modifier.align(CenterHorizontally),
        )
        SpacerH10()
        Text(
            text = stringResourceSafe(id = R.string.express_exchange_status_subtitle),
            style = TangemTheme.typography.caption2,
            color = TangemTheme.colors.text.secondary,
            textAlign = TextAlign.Center,
            modifier = Modifier
                .align(CenterHorizontally),
        )
        SpacerH16()
        ExpressEstimate(
            timestamp = state.info.timestampFormatted,
            fromTokenIconState = state.info.fromCurrencyIcon,
            toTokenIconState = state.info.toCurrencyIcon,
            fromCryptoAmount = state.info.fromAmount,
            fromCryptoSymbol = state.info.fromAmountSymbol,
            toCryptoAmount = state.info.toAmount,
            toCryptoSymbol = state.info.toAmountSymbol,
            fromFiatAmount = state.info.fromFiatAmount,
            toFiatAmount = state.info.toFiatAmount,
        )
        SpacerH12()
        ExpressProvider(
            providerName = TextReference.Str(state.provider.name),
            providerType = TextReference.Str(state.provider.type.providerName),
            providerTxId = state.info.txExternalId,
            imageUrl = state.provider.imageLarge,
        )
        SpacerH12()
        if (extraContent != null) {
            extraContent()
            SpacerH12()
        }
        ExpressStatusBlock(state = state.toExpressStatusUM())
        if (state.notification != null) {
            Notification(state = state.notification, activeStatus = state.activeStatus)
        }
        ExpressHideButton(
            isTerminal = state.activeStatus?.isTerminal == true,
            isAutoDisposable = state.activeStatus?.isAutoDisposable == true,
            onClick = state.info.onDisposeExpressStatus,
        )
        if (isExpressShareButtonEnabled) {
            SpacerH(80.dp)
        } else {
            SpacerH24()
        }
    }
}

private fun ExchangeUM.toExpressStatusUM(): ExpressStatusUM = ExpressStatusUM(
    title = resourceReference(R.string.express_exchange_status_title),
    link = if (showProviderLink) {
        ExpressLinkUM.Content(
            icon = R.drawable.ic_arrow_top_right_24,
            text = resourceReference(R.string.common_go_to_provider),
            onClick = { info.onGoToProviderClick(info.txExternalUrl.orEmpty()) },
        )
    } else {
        ExpressLinkUM.Empty
    },
    statuses = statuses.map { it.toExpressStatusItemUM() }.toImmutableList(),
)

private fun ExchangeStatusState.toExpressStatusItemUM(): ExpressStatusItemUM = ExpressStatusItemUM(
    text = text,
    state = when {
        status == ExchangeStatus.Cancelled -> ExpressStatusItemState.Error
        status.isFailed() || status == ExchangeStatus.Refunded || status == ExchangeStatus.Paused -> {
            if (isDone) ExpressStatusItemState.Done else ExpressStatusItemState.Error
        }
        status == ExchangeStatus.Verifying -> ExpressStatusItemState.Warning
        isDone -> ExpressStatusItemState.Done
        isActive -> ExpressStatusItemState.Active
        else -> ExpressStatusItemState.Default
    },
)

@Composable
private fun Notification(state: ExchangeStatusNotification, activeStatus: ExchangeStatus?) {
    AnimatedContent(
        targetState = state,
        modifier = Modifier.padding(top = TangemTheme.dimens.spacing12),
        label = "Exchange Status Notification Change",
        contentKey = { it::class.java },
    ) { notification ->
        when (notification) {
            is ExchangeStatusNotification.CommonNotification -> {
                com.tangem.core.ui.components.notifications.Notification(
                    config = notification.config,
                    iconTint = when {
                        activeStatus == ExchangeStatus.Verifying -> TangemTheme.colors.icon.attention
                        activeStatus.isFailed() -> TangemTheme.colors.icon.warning
                        else -> null
                    },
                    containerColor = TangemTheme.colors.background.action,
                )
            }
            is ExchangeStatusNotification.TokenRefunded -> {
                CurrencyNotification(
                    config = notification.config,
                    containerColor = TangemTheme.colors.background.action,
                )
            }
        }
    }
}