package com.isidroid.c23.ui.screen.render_preview

import android.util.SparseArray
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.consumeWindowInsets
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.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition
import com.isidroid.c23.R
import com.isidroid.c23.ui._component.TopAppBarComponent
import com.isidroid.c23.ui.screen.render_preview._component.PagerPreviewComponent
import com.isidroid.c23.ui.screen.render_preview._component.PaperInfoComponent
import com.isidroid.c23.ui.screen.render_preview._component.PreviewFooterComponent
import com.isidroid.c23.ui.screen.render_preview._component.PrintCopiesModalComponent
import com.isidroid.c23.ui.screen.render_preview._component.PrintOptionsComponent
import com.isidroid.c23.ui.screen.render_preview._component.PrintOrientationModalComponent
import com.isidroid.c23.ui.screen.render_preview._component.PrintProfileListSelectorComponent
import com.isidroid.c23.ui.screen.render_preview._component.PrintSizeModalComponent
import com.isidroid.c23.ui.screen.render_preview._component.SpotHasNotPrintProfilesComponent
import com.isidroid.core.vm.SIDE_EFFECTS_KEY
import com.isidroid.rendering.model.RenderResult
import com.isidroid.spot.model.PrintProfile
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RenderPreviewScreen(
    state: State<RenderContract.State>,
    renderResultsFlow: StateFlow<SparseArray<RenderResult>?>?,
    onEventSent: (event: RenderContract.Event) -> Unit,
    onNavigationRequested: (navigationEffect: RenderContract.Effect.Navigation) -> Unit,
    modifier: Modifier = Modifier,
    effectFlow: Flow<RenderContract.Effect>?
) {
    val context = LocalContext.current
    val openPrintSize = state.value.openPrintSize
    val openOrientation = state.value.openOrientation
    val copies = state.value.openCopies
    val spotHasNoPrintProfiles = state.value.spotHasNoPrintProfiles
    val printProfileSelector = state.value.printProfilesSelector
    val bottomColor = MaterialTheme.colorScheme.secondaryContainer

    var pagerPage by remember { mutableIntStateOf(-1) }

    LaunchedEffect(SIDE_EFFECTS_KEY) {
        effectFlow?.collect { effect ->
            when (effect) {
                is RenderContract.Effect.Navigation -> onNavigationRequested(effect)
                RenderContract.Effect.PrintJobCreated -> Toast.makeText(context, R.string.print_job_sending, Toast.LENGTH_SHORT).show()
            }
        }
    }

    BackHandler {
        onEventSent(RenderContract.Event.ToBack)
    }

    if (state.value.rendering) {
        val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.convert))

        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {

            Column {
                LottieAnimation(
                    composition = composition,
                    iterations = LottieConstants.IterateForever,
                    modifier = modifier
                        .fillMaxWidth()
                        .padding(48.dp)

                )

                Text(
                    text = "Please wait until convert is completed",
                    style = MaterialTheme.typography.labelLarge,
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Center
                )
            }
        }

        return
    }

    when {
        spotHasNoPrintProfiles -> {
            SpotHasNotPrintProfilesComponent(
                onConfirmClick = { onEventSent(RenderContract.Event.OpenMap) },
                onDismissRequest = { onEventSent(RenderContract.Event.ToBack) }
            )

            return
        }

        printProfileSelector != null -> PrintProfileListSelectorComponent(
            list = printProfileSelector,
            current = state.value.printProfile,
            onChange = { onEventSent(RenderContract.Event.ChangePrintProfile(it, page = pagerPage)) }
        )

        openPrintSize != null -> PrintSizeModalComponent(
            currentPrintSize = openPrintSize,
            onSelect = { onEventSent(RenderContract.Event.UpdateRenderSettings(size = it, page = pagerPage)) }
        )

        openOrientation != null -> PrintOrientationModalComponent(
            currentOrientation = openOrientation,
            onSelect = { onEventSent(RenderContract.Event.UpdateRenderSettings(orientation = it, page = pagerPage)) }
        )

        copies != null -> PrintCopiesModalComponent(
            copies = copies,
            onChange = { increaseCopy -> onEventSent(RenderContract.Event.UpdateRenderSettings(increaseCopy = increaseCopy, page = pagerPage)) },
        )

    }

    Scaffold(
        modifier = modifier.fillMaxSize(),
        topBar = {
            TopAppBarComponent(
                text = stringResource(id = R.string.appbar_print_preview),
                alpha = .65f,
                onNavigationClick = { onEventSent(RenderContract.Event.ToBack) }
            )
        }
    ) { paddingValues ->
        val bottomPaddings = paddingValues.calculateBottomPadding()
        val topPadding = paddingValues.calculateTopPadding() + 6.dp

        ConstraintLayout(
            modifier = modifier
                .padding(top = topPadding)
                .consumeWindowInsets(paddingValues)
                .fillMaxSize()
        ) {
            val (footer, spotView, printOptions, paperInfo, pager) = createRefs()

            PagerPreviewComponent(
                state = state,
                renderResultsFlow = renderResultsFlow,
                modifier = Modifier
                    .fillMaxWidth()
                    .constrainAs(pager) {
                        linkTo(top = parent.top, bottom = paperInfo.top)
                        height = Dimension.fillToConstraints
                    },
                onPageOpened = { page, containerSize ->
                    pagerPage = page
                    onEventSent(RenderContract.Event.OnPageOpened(page, containerSize))
                }
            )

            PaperInfoComponent(
                state = state,
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onEventSent(RenderContract.Event.OpenListProfiles) }
                    .padding(bottom = 12.dp)
                    .padding(horizontal = 16.dp)
                    .constrainAs(paperInfo) { bottom.linkTo(printOptions.top) }
            )

            PrintOptionsComponent(
                renderSettingsV2 = state.value.renderSettings,
                modifier = Modifier.constrainAs(printOptions) { bottom.linkTo(spotView.top) },
                clickOnCopies = { onEventSent(RenderContract.Event.OpenCopiesSettings) },
                clickOnPrintSize = { onEventSent(RenderContract.Event.OpenPrintSizeSettings) },
                clickOnOrientation = { onEventSent(RenderContract.Event.OpenOrientationSettings) },
            )


            PreviewFooterComponent(
                state = state,
                bottomColor = bottomColor,
                modifier = Modifier.constrainAs(spotView) { bottom.linkTo(footer.top) },
                onEventSent = onEventSent
            )

            Box(modifier = Modifier
                .fillMaxWidth()
                .height(bottomPaddings)
                .background(bottomColor)
                .constrainAs(footer) { bottom.linkTo(parent.bottom) })
        }
    }
}


@Preview(
    device = Devices.PIXEL_4,
    showSystemUi = true
)
@Composable
private fun RenderPreviewScreenPreview() {
    Surface(Modifier.fillMaxSize()) {
        RenderPreviewScreen(
            state = remember {
                mutableStateOf(
                    RenderContract.State(
                        printProfile = PrintProfile(name = "Test")
                    )
                )
            },
            renderResultsFlow = null,
            onEventSent = {},
            onNavigationRequested = {},
            effectFlow = null,
        )
    }
}



