package ch.threema.app.multidevice.wizard.steps

import android.annotation.SuppressLint
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.platform.rememberNestedScrollInteropConnection
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import ch.threema.app.R
import ch.threema.app.compose.common.buttons.primary.ButtonPrimary
import ch.threema.app.compose.common.spacer.DynamicSpacerSize1
import ch.threema.app.compose.common.spacer.DynamicSpacerSize4
import ch.threema.app.compose.common.text.ThemedText
import ch.threema.app.compose.preview.PreviewThreemaPhoneAll
import ch.threema.app.compose.theme.ThreemaTheme
import ch.threema.app.compose.theme.ThreemaThemePreview
import ch.threema.app.compose.theme.dimens.GridUnit
import ch.threema.app.multidevice.wizard.LinkingResult
import ch.threema.app.utils.ConfigUtils
import ch.threema.app.utils.logScreenVisibility
import ch.threema.base.utils.getThreemaLogger
import java.time.Instant

private val logger = getThreemaLogger("LinkNewDeviceResultFragment")

class LinkNewDeviceResultFragment : LinkNewDeviceFragment() {
    init {
        logScreenVisibility(logger)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return ComposeView(requireContext()).apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                ThreemaTheme {
                    val linkingResult by viewModel.linkingResult.collectAsStateWithLifecycle()
                    LinkNewDeviceResultContent(
                        modifier = Modifier.fillMaxSize(),
                        linkingResult = linkingResult ?: LinkingResult.Failure.Unexpected,
                        onClickPrimary = {
                            viewModel.switchToFragment(null)
                        },
                    )
                }
            }
        }
    }

    @SuppressLint("MissingSuperCall")
    override fun onConfigurationChanged(newConfig: Configuration) {
        // Explicitly doing nothing, as we update the top padding using windowInsetsTopHeight from Compose
    }
}

@Composable
fun LinkNewDeviceResultContent(
    modifier: Modifier,
    linkingResult: LinkingResult,
    onClickPrimary: () -> Unit,
) {
    Surface(
        modifier = modifier.nestedScroll(rememberNestedScrollInteropConnection()),
        color = MaterialTheme.colorScheme.surfaceContainerLow,
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = dimensionResource(R.dimen.grid_unit_x4))
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Spacer(Modifier.windowInsetsTopHeight(WindowInsets.systemBars))

            DynamicSpacerSize1()

            val context = LocalContext.current
            Icon(
                modifier = Modifier.size(120.dp),
                painter = painterResource(linkingResult.iconRes),
                contentDescription = null,
                tint = linkingResult.iconTintAttrRes?.let { colorAttrId ->
                    Color(ConfigUtils.getColorFromAttribute(context, colorAttrId))
                } ?: Color.Unspecified,
            )

            Spacer(Modifier.height(GridUnit.x6))

            ThemedText(
                text = linkingResult.resolveTitleText(LocalContext.current),
                textAlign = TextAlign.Center,
                style = MaterialTheme.typography.headlineSmall,
            )

            Spacer(Modifier.height(GridUnit.x4))

            Text(
                text = linkingResult.resolveBodyText(LocalContext.current),
                textAlign = TextAlign.Center,
                style = MaterialTheme.typography.bodyMedium,
            )

            Spacer(Modifier.height(GridUnit.x6))

            ButtonPrimary(
                modifier = Modifier.fillMaxWidth(),
                onClick = onClickPrimary,
                text = stringResource(linkingResult.primaryButtonTextRes),
                maxLines = 2,
            )

            DynamicSpacerSize4()
        }
    }
}

@Composable
@PreviewThreemaPhoneAll
fun LinkNewDeviceResultContentPreviewFailure() = ThreemaThemePreview {
    LinkNewDeviceResultContent(
        modifier = Modifier.fillMaxSize(),
        linkingResult = LinkingResult.Failure.UnknownQrCode,
        onClickPrimary = {},
    )
}

@Composable
@PreviewThreemaPhoneAll
fun LinkNewDeviceResultContentPreviewFailureInvalidTimestamp() = ThreemaThemePreview {
    LinkNewDeviceResultContent(
        modifier = Modifier.fillMaxSize(),
        linkingResult = LinkingResult.Failure.InvalidTimestamp(
            description = "Invalid Timestamp XYZ",
            timestamp = Instant.now().toEpochMilli() * -1,
        ),
        onClickPrimary = {},
    )
}

@Composable
@PreviewThreemaPhoneAll
fun LinkNewDeviceResultContentPreviewSuccess() = ThreemaThemePreview {
    LinkNewDeviceResultContent(
        modifier = Modifier.fillMaxSize(),
        linkingResult = LinkingResult.Success,
        onClickPrimary = {},
    )
}
