package com.isidroid.c23.ui.screen.details.component

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
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.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
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.details.JobDetailsContract
import com.isidroid.c23.ui.screen.map.MapContract
import com.isidroid.c23.ui.screen.map._components.TPMapComponent
import com.isidroid.core.vm.SIDE_EFFECTS_KEY
import com.isidroid.ui.maps.model.MapMarker
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DetailsV1(
    state: State<JobDetailsContract.State>,
    effectFlow: Flow<JobDetailsContract.Effect>?,
    spotResultStateFlow: StateFlow<List<MapMarker>>,
    onEventSent: (event: JobDetailsContract.Event) -> Unit,
    onNavigationRequested: (navigationEffect: JobDetailsContract.Effect.Navigation) -> Unit,
    modifier: Modifier = Modifier,
){
    LaunchedEffect(SIDE_EFFECTS_KEY) {
        effectFlow?.collect { effect ->
            when (effect) {
                is JobDetailsContract.Effect.Navigation -> onNavigationRequested(effect)
            }
        }
    }

    BackHandler { onEventSent(JobDetailsContract.Event.ToBack) }

    Scaffold(
        modifier = modifier.fillMaxSize(),
        topBar = {
            TopAppBarComponent(
                text = stringResource(id = R.string.print_job_details),
                colors = TopAppBarDefaults.topAppBarColors(),
                onNavigationClick = { onEventSent(JobDetailsContract.Event.ToBack) }
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .consumeWindowInsets(paddingValues)
                .padding(top = paddingValues.calculateTopPadding())
                .fillMaxSize(),
            contentAlignment = Alignment.TopStart
        ) {
            when {
                state.value.isLoading -> LoadingComponent()
            }

            InformationContent(state, spotResultStateFlow, onEventSent)
            DisplayMapRouteConfirmation(state, onEventSent)
        }
    }
}


@Composable
private fun LoadingComponent(modifier: Modifier = Modifier) {
    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.startapp))
    LottieAnimation(
        composition = composition,
        iterations = LottieConstants.IterateForever,
        modifier = modifier
            .fillMaxSize()
            .padding(48.dp)
    )
}


@Composable
private fun InformationContent(
    state: State<JobDetailsContract.State>,
    spotResultStateFlow: StateFlow<List<MapMarker>>,
    onEventSent: (event: JobDetailsContract.Event) -> Unit,
    modifier: Modifier = Modifier
) {
    val information = state.value.printJob ?: return

    ConstraintLayout(modifier = modifier.fillMaxSize()) {
        val (codeView, statusView, mapView) = createRefs()

        PrintCodeComponent(
            code = information.accessCode,
            modifier = Modifier
                .constrainAs(codeView) {
                    top.linkTo(parent.top)
                    linkTo(start = parent.start, end = parent.end)
                }
        )

        Text(
            text = information.statusName,
            fontSize = 14.sp,
            fontWeight = FontWeight.W200,
            letterSpacing = .76.sp,
            color = Color.White,
            modifier = Modifier
                .clip(RoundedCornerShape(6.dp))
                .background(information.statusColor)
                .padding(horizontal = 6.dp, vertical = 2.dp)
                .constrainAs(statusView) {
                    top.linkTo(codeView.bottom, 12.dp)
                    end.linkTo(parent.end, 12.dp)
                }
        )

        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 12.dp)
                .constrainAs(mapView) {
                    linkTo(top = statusView.bottom, bottom = parent.bottom)
                    height = Dimension.fillToConstraints
                },
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp, bottomStart = 0.dp, bottomEnd = 0.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 12.dp)
        ) {
            TPMapComponent(
                modifier = Modifier,
                onEventSent = { event ->
                    when (event) {
                        is MapContract.Event.ClickOnMarker -> onEventSent(JobDetailsContract.Event.OpenConfirmationMapRoute)
                        else -> {}
                    }
                },
                mapMarkersStateFlow = spotResultStateFlow,
                lat = state.value.lat,
                lng = state.value.lng
            )
        }
    }
}