package llc.arma.ble.app.ui.screen.rotation.statistic

import android.icu.text.SimpleDateFormat
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
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.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.ArrowForward
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.DatePicker
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
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.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.hilt.navigation.compose.hiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.util.Date
import java.util.concurrent.TimeUnit
import kotlin.math.absoluteValue
import kotlin.math.pow
import kotlin.math.roundToInt

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RotationStatisticScreen(
    onNavigation: (RotationStatisticContract.Effect.Navigation) -> Unit
) {

    val viewModel = hiltViewModel<RotationStatisticViewModel>()
    val state = viewModel.viewState.value

    LaunchedEffect(Unit) {
        viewModel.effect.onEach {
            when(it){
                is RotationStatisticContract.Effect.Navigation -> onNavigation(it)
            }
        }.launchIn(this)
    }

    Column(

        modifier = Modifier.fillMaxSize()
    ) {

        TopAppBar(
            navigationIcon = {
                IconButton(
                    onClick = {
                        viewModel.setEvent(RotationStatisticContract.Event.OnNavigateUp)
                    }
                ) {
                    Icon(
                        imageVector = Icons.Rounded.ArrowBack,
                        contentDescription = null
                    )
                }
            },
            title = {
                Text(
                    modifier = Modifier.weight(1f),
                    text = "Обороты",
                    style = MaterialTheme.typography.titleLarge
                )
            },
            actions = {
                IconButton(
                    onClick = {
                        viewModel.setEvent(RotationStatisticContract.Event.OnNavigateToDelete)
                    }
                ) {
                    Icon(
                        imageVector = Icons.Rounded.Delete,
                        contentDescription = null
                    )
                }
            }
        )

        Column(
            verticalArrangement = Arrangement.spacedBy(16.dp),
            modifier = Modifier.padding(12.dp)
        ) {

            if(state is RotationStatisticContract.State.Display){

                var showStartDateSelector by remember {
                    mutableStateOf(false)
                }

                var showEndDateSelector by remember {
                    mutableStateOf(false)
                }

                Row(
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {

                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .width(IntrinsicSize.Max)
                            .height(IntrinsicSize.Max)
                    ) {

                        TextField(
                            readOnly = true,
                            value = dateFormat.format(Date(state.startDate ?: state.ranges.minOfOrNull { it.startDate } ?: 0)),
                            onValueChange = {},
                            label = {
                                Text(text = "Начало")
                            },

                        )

                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .clickable { showStartDateSelector = true }
                        ) {}

                    }

                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .width(IntrinsicSize.Max)
                            .height(IntrinsicSize.Max)
                    ) {

                        TextField(
                            readOnly = true,
                            value = dateFormat.format(Date(state.endDate ?: state.ranges.maxOfOrNull { it.endDate } ?: 0)),
                            onValueChange = {},
                            label = {
                                Text(text = "Завершение")
                            }
                        )

                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .clickable { showEndDateSelector = true }
                        ) {}

                    }

                }

                TextField(
                    singleLine = true,
                    value = state.radius?.toString() ?: "",
                    onValueChange = {
                        viewModel.setEvent(
                            RotationStatisticContract.Event.OnRadiusChanged(
                                it.filter { it.isDigit() }.toLongOrNull()
                            )
                        )
                    },
                    label = {
                        Text(text = "Радиус колеса (мм.)")
                    },
                    modifier = Modifier.fillMaxWidth()
                )

                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {

                    Column {

                        Text(text = "Пройденное расстояние")
                        Text(text = "Движение вперед")
                        Text(text = "Движение назад")
                        Text(text = "Стоянка")

                    }

                    Column {

                        val duration = state.ranges.filter { it.distance == 0.0 }.sumOf { it.endDate - it.startDate }
                        val hours = duration / TimeUnit.HOURS.toMillis(1)
                        val minutes = (duration - (hours * TimeUnit.HOURS.toMillis(1))) / TimeUnit.MINUTES.toMillis(1)
                        val seconds = (duration - (hours * TimeUnit.HOURS.toMillis(1)) - (minutes * TimeUnit.MINUTES.toMillis(1))) / TimeUnit.SECONDS.toMillis(1)

                        Text(text = state.ranges.sumOf { it.distance.absoluteValue }.roundTo().toString() + " м.")
                        Text(text = state.ranges.filter { it.distance > 0 }.sumOf { it.distance.absoluteValue }.roundTo().toString() + " м.")
                        Text(text = state.ranges.filter { it.distance < 0 }.sumOf { it.distance.absoluteValue }.roundTo().toString() + " м.")
                        Text(text = "${hours}ч ${minutes}м. ${seconds}с.")

                    }

                }

                var reversed by remember {
                    mutableStateOf(true)
                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                    modifier = Modifier.fillMaxWidth()
                ) {

                    Text(text = "Порядок")

                    IconButton(
                        onClick = { reversed = reversed.not() }
                    ) {

                        Icon(
                            imageVector = if (reversed) Icons.Rounded.ArrowBack else Icons.Rounded.ArrowForward,
                            contentDescription = null
                        )

                    }

                }

                LazyRow(
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {

                    items(items = state.ranges.let { if (reversed) it.reversed() else it}){
                        DataRange(range = it)
                    }

                }

                if(showStartDateSelector) {

                    Dialog(
                        properties = DialogProperties(usePlatformDefaultWidth = false),
                        onDismissRequest = {
                            showEndDateSelector = false
                        }
                    ) {

                        Surface(
                            shape = RoundedCornerShape(16.dp)
                        ) {

                            val datePickerState = rememberDatePickerState(
                                initialSelectedDateMillis = state.startDate
                            )

                            Column{

                                DatePicker(state = datePickerState)

                                Row(
                                    horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
                                    modifier = Modifier
                                        .align(Alignment.End)
                                        .padding(12.dp)
                                ) {

                                    TextButton(
                                        onClick = {
                                            showStartDateSelector = false
                                        }
                                    ) {
                                        Text(text = "Отмена")
                                    }

                                    Button(
                                        onClick = {
                                            viewModel.setEvent(
                                                RotationStatisticContract.Event.OnStartDateChanged(
                                                    datePickerState.selectedDateMillis ?: state.startDate
                                                )
                                            )
                                            showStartDateSelector = false
                                        }
                                    ) {
                                        Text(text = "ок")
                                    }

                                }

                            }

                        }

                    }

                }

                if(showEndDateSelector) {

                    Dialog(
                        properties = DialogProperties(usePlatformDefaultWidth = false),
                        onDismissRequest = {
                            showEndDateSelector = false
                        }
                    ) {

                        Surface(
                            shape = RoundedCornerShape(16.dp)
                        ) {

                            val datePickerState = rememberDatePickerState(
                                initialSelectedDateMillis = state.endDate
                            )

                            Column {

                                DatePicker(state = datePickerState)

                                Row(
                                    horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
                                    modifier = Modifier
                                        .align(Alignment.End)
                                        .padding(12.dp)
                                ) {

                                    TextButton(
                                        onClick = {
                                            showEndDateSelector = false
                                        }
                                    ) {
                                        Text(text = "Отмена")
                                    }

                                    Button(
                                        onClick = {
                                            viewModel.setEvent(
                                                RotationStatisticContract.Event.OnStopDateChanged(
                                                    datePickerState.selectedDateMillis ?: state.endDate
                                                )
                                            )
                                            showEndDateSelector = false
                                        }
                                    ) {
                                        Text(text = "ок")
                                    }

                                }

                            }

                        }

                    }

                }

            }

        }

    }

}

fun Double.roundTo(numFractionDigits: Int = 2): Double {
    val factor = 10.0.pow(numFractionDigits.toDouble())
    return (this * factor).roundToInt() / factor
}

private fun Double.round(decimals: Int = 2): Double = "%.${decimals}f".format(this).toDouble()

private val dateTimeFormat = SimpleDateFormat("dd.MM HH:mm:ss")
private val dateFormat = SimpleDateFormat("dd.MM HH:mm:ss")

@Composable
private fun DataRange(range: RotationStatisticContract.State.Display.RotationRange){

    Card {

        Column(
            modifier = Modifier
                .padding(12.dp)
                .width(IntrinsicSize.Max)
        ) {

            val duration = range.endDate - range.startDate
            val hours = duration / TimeUnit.HOURS.toMillis(1)
            val minutes = (duration - (hours * TimeUnit.HOURS.toMillis(1))) / TimeUnit.MINUTES.toMillis(1)
            val seconds = (duration - (hours * TimeUnit.HOURS.toMillis(1)) - (minutes * TimeUnit.MINUTES.toMillis(1))) / TimeUnit.SECONDS.toMillis(1)

            val directionText = if(range.distance > 0){
                "-->"
            }else{
                if(range.distance < 0) {
                    "<--"
                } else {
                    "<<P>>"
                }
            }



            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {

                Column {

                    Text(text = "Начало")
                    Text(text = "Конец")

                }

                Column {

                    Text(text = dateTimeFormat.format(Date(range.startDate)))
                    Text(text = dateTimeFormat.format(Date(range.endDate)))


                }

            }

            Text(text = "Направление: " + directionText)

            HorizontalDivider()

            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {

                Column {

                    Text(text = "Время")

                    if(range.distance != 0.0) {

                        Text(text = "Расстояние")
                        Text(text = "Vmax.")
                        Text(text = "Vср.")
                        Text(text = "Обороты")

                    }

                }

                Column {

                    Text(text = "${hours}ч ${minutes}м. ${seconds}с.")

                    if(range.distance != 0.0) {

                        Text(text = range.distance.absoluteValue.roundTo().toString() + " м.")
                        Text(text = range.maxSpeed.roundTo().toString() + " Км/ч")
                        Text(text = range.avgSpeed.roundTo().toString() + " Км/ч")
                        Text(text = range.rotations.absoluteValue.toDouble().roundTo().toString())

                    }

                }

            }



        }

    }

}