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

import android.util.SparseArray
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.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.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
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.isidroid.c23.R
import com.isidroid.c23.ui._component.ShortOfficeInfoComponent
import com.isidroid.c23.ui._component.TopAppBarComponent
import com.isidroid.rendering.model.RenderResult
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.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.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 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

    LaunchedEffect(SIDE_EFFECTS_KEY) {
        effectFlow?.collect { effect ->
            when (effect) {
                is RenderContract.Effect.Navigation -> onNavigationRequested(effect)
            }
        }
    }

    BackHandler {
        onEventSent(RenderContract.Event.ToBack)
    }

    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)) }
        )

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

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

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

    }

    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 -> 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) },
            )


            ShortOfficeInfoComponent(
                officeName = "officeName",
                bottomColor = bottomColor,
                modifier = Modifier
                    .fillMaxWidth()
                    .constrainAs(spotView) { bottom.linkTo(footer.top) },
                containerClick = {},
                titleRes = R.string.preview_footer_title,
                buttonTextRes = R.string.action_print
            )

            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,
        )
    }
}



