package llc.arma.ble.app.ui.screen.inspection.accelerometer.view

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.KeyboardArrowDown
import androidx.compose.material.icons.rounded.KeyboardArrowUp
import androidx.compose.material3.FilledIconButton
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.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import llc.arma.ble.app.ui.model.BleView
import llc.arma.ble.app.ui.screen.inspection.accelerometer.AccelerometerContract

@Composable
fun IntervalEdit(
    state: BleView.Accelerometer,
    onEvent: (AccelerometerContract.Event) -> Unit,
){

    var value by remember(state.accelerometerState.historyInterval) {
        mutableIntStateOf((state.accelerometerState.historyInterval).toInt())
    }

    val maxInterval = 10 * 24 * 60 * 60 * 1000
    val minInterval = 10_000

    if(value > maxInterval){
        value = maxInterval
    }

    if(value < minInterval){
        value = minInterval
    }

    val maxSeconds = maxInterval / millisInSecond
    val maxMinutes = maxInterval / millisInMinute
    val maxHours = maxInterval / millisInHour
    val maxDays = maxInterval / millisInDay

    val dayValue = value / millisInDay
    val hourValue = (value - (dayValue * millisInDay)) / millisInHour
    val minutesValue = (value - (dayValue * millisInDay) - (hourValue * millisInHour)) / millisInMinute
    val secondsValue = (value - (dayValue * millisInDay) - (hourValue * millisInHour) - (minutesValue * millisInMinute)) / millisInSecond

    Column(
        modifier = Modifier
    ) {

        Text(
            modifier = Modifier.padding(horizontal = 12.dp),
            text = "Интервал измерений",
            style = MaterialTheme.typography.titleLarge
        )

        Spacer(modifier = Modifier.height(16.dp))


        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.align(Alignment.CenterHorizontally)
        ) {

            NumberPicker(
                range = -1..maxDays,
                value = dayValue,
                onValueChanged = {
                    value = (it * millisInDay) + (hourValue * millisInHour) + (minutesValue * millisInMinute) + (secondsValue * millisInSecond)
                }
            )

            Spacer(modifier = Modifier.width(8.dp))

            Text(text = "Д.")

            Spacer(modifier = Modifier.width(16.dp))

            NumberPicker(
                range = -1..maxHours,
                value = hourValue,
                onValueChanged = {
                    value = (it * millisInHour) + (dayValue * millisInDay) + (minutesValue * millisInMinute) + (secondsValue * millisInSecond)
                }
            )

            Spacer(modifier = Modifier.width(8.dp))

            Text(text = "Ч.")

            Spacer(modifier = Modifier.width(16.dp))

            NumberPicker(
                range = -1..maxMinutes,
                value = minutesValue,
                onValueChanged = {
                    value = (secondsValue * millisInSecond) + (it * millisInMinute) + (dayValue * millisInDay) + (hourValue * millisInHour)
                }
            )

            Spacer(modifier = Modifier.width(8.dp))

            Text(text = "М.")

            Spacer(modifier = Modifier.width(16.dp))

            NumberPicker(
                range = -1..maxSeconds,
                value = secondsValue,
                onValueChanged = {
                    value = (it * millisInSecond) + (minutesValue * millisInMinute) + (dayValue * millisInDay) + (hourValue * millisInHour)
                }
            )

            Spacer(modifier = Modifier.width(8.dp))

            Text(text = "С.")

        }

        Spacer(modifier = Modifier.height(16.dp))

        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp)
                .height(50.dp),
            shape = CircleShape,
            color = MaterialTheme.colorScheme.primaryContainer,
            onClick = {
                onEvent(
                    AccelerometerContract.Event.OnSaveIntervalChanged(
                        value.toLong()
                    )
                )
            }
        ) {

            Box(modifier = Modifier.fillMaxSize()) {

                Text(
                    modifier = Modifier.align(Alignment.Center),
                    color = MaterialTheme.colorScheme.background,
                    style = MaterialTheme.typography.labelLarge,
                    text = "Применить"
                )

            }

        }

    }

}

const val millisInSecond = 1000
const val millisInMinute = millisInSecond * 60
const val millisInHour = millisInMinute * 60
const val millisInDay = millisInHour * 24


@Composable
fun NumberPicker(
    modifier: Modifier = Modifier,
    range: IntRange,
    value: Int,
    onValueChanged: (Int) -> Unit
) {

    LaunchedEffect(range){

        if(value > range.last){

            onValueChanged(range.last)

        }

        if(value < range.first){

            onValueChanged(range.first)

        }

    }

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
    ){

        FilledIconButton(
            onClick = {
                if(value < range.last) onValueChanged(value + 1)
            }
        ) {
            Icon(
                imageVector = Icons.Rounded.KeyboardArrowUp,
                contentDescription = null
            )
        }

        Spacer(modifier = Modifier.height(36.dp))

        AnimatedContent(
            targetState = value,
            transitionSpec = {
                if (targetState > initialState) {
                    (slideInVertically { height -> height } + fadeIn()).togetherWith(
                        slideOutVertically { height -> -height } + fadeOut())
                } else {
                    (slideInVertically { height -> -height } + fadeIn()).togetherWith(
                        slideOutVertically { height -> height } + fadeOut())
                }.using(
                    SizeTransform(clip = false)
                )
            }
        ) { targetCount ->
            Text(
                style = MaterialTheme.typography.displaySmall,
                text = "$targetCount"
            )
        }

        Spacer(modifier = Modifier.height(36.dp))

        FilledIconButton(
            onClick = {
                if(value > range.first) onValueChanged(value - 1)

            }
        ) {
            Icon(
                imageVector = Icons.Rounded.KeyboardArrowDown,
                contentDescription = null
            )
        }

    }


}