package com.tangem.features.details.ui

import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastForEach
import com.tangem.core.ui.components.SpacerH16
import com.tangem.core.ui.components.appbar.TangemTopAppBar
import com.tangem.core.ui.components.appbar.models.TopAppBarButtonUM
import com.tangem.core.ui.components.block.BlockCard
import com.tangem.core.ui.components.block.BlockItem
import com.tangem.core.ui.decompose.ComposableContentComponent
import com.tangem.core.ui.ds.image.TangemIcon
import com.tangem.core.ui.ds.image.TangemIconUM
import com.tangem.core.ui.ds2.row.TangemRow
import com.tangem.core.ui.ds2.row.TangemRowText
import com.tangem.core.ui.ds2.row.TangemRowTextRole
import com.tangem.core.ui.ds2.row.TangemRowVerticalAlignment
import com.tangem.core.ui.extensions.TextReference
import com.tangem.core.ui.extensions.resolveReference
import com.tangem.core.ui.extensions.stringResourceSafe
import com.tangem.core.ui.res.TangemTheme
import com.tangem.core.ui.res.TangemThemePreview
import com.tangem.core.ui.res.generated.icons.Icons
import com.tangem.core.ui.res.generated.icons.ic_chevron_right_20
import com.tangem.core.ui.test.DetailsScreenTestTags
import com.tangem.features.details.component.preview.PreviewDetailsComponent
import com.tangem.features.details.entity.DetailsFooterUM
import com.tangem.features.details.entity.DetailsItemUM
import com.tangem.features.details.entity.DetailsUM
import com.tangem.features.details.impl.R
import kotlinx.collections.immutable.ImmutableList

@Composable
internal fun DetailsScreen(
    state: DetailsUM,
    userWalletListBlockContent: ComposableContentComponent,
    modifier: Modifier = Modifier,
) {
    val backgroundColor = TangemTheme.colors.background.secondary

    Scaffold(
        modifier = modifier,
        containerColor = backgroundColor,
        topBar = {
            TangemTopAppBar(
                modifier = Modifier.statusBarsPadding(),
                startButton = TopAppBarButtonUM.Back(state.popBack),
            )
        },
    ) { paddingValues ->
        Content(
            modifier = Modifier.padding(paddingValues),
            state = state,
            userWalletListBlockContent = userWalletListBlockContent,
        )
    }

    SelectFeedbackEmailTypeBottomSheet(state.selectFeedbackEmailTypeBSConfig)
    SelectContactSupportTypeBottomSheet(state.selectContactSupportTypeBSConfig)
}

@Composable
private fun Content(
    state: DetailsUM,
    userWalletListBlockContent: ComposableContentComponent,
    modifier: Modifier = Modifier,
) {
    LazyColumn(
        modifier = modifier.testTag(DetailsScreenTestTags.SCREEN_CONTAINER),
        verticalArrangement = Arrangement.SpaceBetween,
        contentPadding = PaddingValues(
            top = TangemTheme.dimens.spacing12,
            bottom = TangemTheme.dimens.spacing16,
        ),
    ) {
        item {
            Text(
                modifier = Modifier.padding(horizontal = TangemTheme.dimens.spacing16),
                text = stringResourceSafe(R.string.details_title),
                style = TangemTheme.typography.h1,
                color = TangemTheme.colors.text.primary1,
            )
        }
        items(
            items = state.items,
            key = DetailsItemUM::id,
        ) { block ->
            Block(
                modifier = Modifier.padding(horizontal = TangemTheme.dimens.spacing16),
                model = block,
                userWalletListBlockContent = userWalletListBlockContent,
            )
        }

        item(key = "footer") {
            SpacerH16()
            Footer(
                modifier = Modifier.padding(horizontal = TangemTheme.dimens.spacing12),
                model = state.footer,
            )
        }
    }
}

@Composable
private fun Block(
    model: DetailsItemUM,
    userWalletListBlockContent: ComposableContentComponent,
    modifier: Modifier = Modifier,
) {
    if (model is DetailsItemUM.UnderSectionText) {
        UnderSectionTextBlock(
            modifier = Modifier.fillMaxWidth(),
            text = model.text,
        )
        return
    }

    SpacerH16()

    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(
                shape = TangemTheme.shapes.roundedCornersXMedium,
                color = TangemTheme.colors.background.primary,
            ),
        horizontalAlignment = Alignment.Start,
        verticalArrangement = Arrangement.Top,
    ) {
        val itemModifier = Modifier
            .fillMaxWidth()
            .testTag(DetailsScreenTestTags.SCREEN_ITEM)

        when (model) {
            is DetailsItemUM.Basic -> {
                model.items.forEach { item ->
                    key(item.id) {
                        BlockItem(
                            modifier = itemModifier,
                            model = item.block,
                        )
                    }
                }
            }
            is DetailsItemUM.WalletConnect -> {
                WalletConnectBlock(
                    modifier = itemModifier,
                    onClick = model.onClick,
                )
            }
            is DetailsItemUM.WalletActionBlock -> {
                BlockCard {
                    WalletActionsBlock(
                        items = model.items,
                        modifier = itemModifier,
                    )
                }
            }
            is DetailsItemUM.UserWalletList -> {
                userWalletListBlockContent.Content(modifier = itemModifier)
            }
            is DetailsItemUM.UnderSectionText -> Unit
        }
    }
}

@Composable
private fun WalletActionsBlock(
    items: ImmutableList<DetailsItemUM.WalletActionBlock.Item>,
    modifier: Modifier = Modifier,
) {
    items.fastForEach { item ->
        when (item) {
            is DetailsItemUM.WalletActionBlock.Item.WalletConnect -> WalletConnectActionRow(
                onClick = item.onClick,
                modifier = modifier,
            )
            is DetailsItemUM.WalletActionBlock.Item.AddressBook -> AddressBookActionRow(
                onClick = item.onClick,
                modifier = modifier,
            )
        }
    }
}

@Composable
private fun WalletConnectActionRow(onClick: () -> Unit, modifier: Modifier = Modifier) {
    TangemRow(
        verticalAlignment = TangemRowVerticalAlignment.Center,
        modifier = modifier,
        onClick = onClick,
        startSlot = {
            TangemIcon(
                tangemIconUM = TangemIconUM.Image(R.drawable.img_wallet_connect_76),
                modifier = Modifier
                    .size(40.dp)
                    .clip(RoundedCornerShape(12.dp)),
            )
        },
        titleSlot = {
            TangemRowText(
                text = TextReference.Res(R.string.wallet_connect_title),
                role = TangemRowTextRole.Title,
            )
        },
        subtitleSlot = {
            TangemRowText(
                text = TextReference.Res(R.string.wallet_connect_subtitle),
                role = TangemRowTextRole.Subtitle,
            )
        },
        endSlot = { ActionRowChevron() },
    )
}

@Composable
private fun AddressBookActionRow(onClick: () -> Unit, modifier: Modifier = Modifier) {
    TangemRow(
        verticalAlignment = TangemRowVerticalAlignment.Center,
        modifier = modifier,
        onClick = onClick,
        startSlot = {
            TangemIcon(
                tangemIconUM = TangemIconUM.Icon(
                    iconRes = R.drawable.ic_address_book_24,
                    tintReference = { TangemTheme.colors3.icon.brand },
                ),
                modifier = Modifier
                    .size(40.dp)
                    .background(
                        color = TangemTheme.colors3.bg.status.infoSubtle,
                        shape = RoundedCornerShape(12.dp),
                    )
                    .padding(8.dp),
            )
        },
        titleSlot = {
            TangemRowText(
                text = TextReference.Res(R.string.address_book_title),
                role = TangemRowTextRole.Title,
            )
        },
        subtitleSlot = {
            TangemRowText(
                text = TextReference.Res(R.string.address_book_description),
                role = TangemRowTextRole.Subtitle,
            )
        },
        endSlot = { ActionRowChevron() },
    )
}

@Composable
private fun ActionRowChevron() {
    Icon(
        imageVector = Icons.ic_chevron_right_20,
        contentDescription = null,
        tint = TangemTheme.colors3.icon.secondary,
    )
}

@Composable
private fun UnderSectionTextBlock(text: TextReference, modifier: Modifier = Modifier) {
    Text(
        modifier = modifier.padding(horizontal = 30.dp, vertical = 8.dp),
        text = text.resolveReference(),
        style = TangemTheme.typography.body2,
        color = TangemTheme.colors.text.tertiary,
    )
}

@Composable
private fun Footer(model: DetailsFooterUM, modifier: Modifier = Modifier) {
    Column(
        modifier = modifier
            .padding(
                top = TangemTheme.dimens.spacing12,
                bottom = TangemTheme.dimens.spacing16,
            )
            .fillMaxWidth(),
        horizontalAlignment = Alignment.Start,
        verticalArrangement = Arrangement.spacedBy(TangemTheme.dimens.spacing16),
    ) {
        val socialsScrollState = rememberScrollState()

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .scrollable(socialsScrollState, orientation = Orientation.Horizontal),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(TangemTheme.dimens.spacing8),
        ) {
            model.socials.forEach { social ->
                key(social.id) {
                    IconButton(
                        modifier = Modifier.size(TangemTheme.dimens.size32),
                        onClick = social.onClick,
                    ) {
                        Icon(
                            modifier = Modifier.size(TangemTheme.dimens.size24),
                            painter = painterResource(id = social.iconResId),
                            tint = TangemTheme.colors.icon.informative,
                            contentDescription = null,
                        )
                    }
                }
            }
        }

        Text(
            modifier = Modifier
                .padding(horizontal = TangemTheme.dimens.spacing6)
                .testTag(DetailsScreenTestTags.VERSION_NAME),
            text = model.appVersion,
            style = TangemTheme.typography.caption2,
            color = TangemTheme.colors.text.tertiary,
        )
    }
}

// region Preview
@Composable
@Preview(showBackground = true, widthDp = 360)
@Preview(showBackground = true, widthDp = 360, uiMode = Configuration.UI_MODE_NIGHT_YES)
private fun Preview_DetailsScreen() {
    TangemThemePreview {
        PreviewDetailsComponent().Content(modifier = Modifier.fillMaxSize())
    }
}
// endregion Preview