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

import android.os.SystemClock
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ContentAlpha
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowRightAlt
import androidx.compose.material.icons.rounded.BatteryFull
import androidx.compose.material.icons.rounded.CompareArrows
import androidx.compose.material.icons.rounded.FilterAlt
import androidx.compose.material.icons.rounded.Link
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import llc.arma.ble.app.ui.common.SignalLevel
import llc.arma.ble.app.ui.common.rememberBottomDialogState
import llc.arma.ble.domain.model.BleInfo
import llc.arma.ble.domain.model.ConnectedBleInfo
import llc.arma.ble.domain.model.BleFilter
import kotlin.math.pow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BleListScreen(
    onNavigationEvent: (BleListContract.Effect.Navigation) -> Unit
) {

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

    val bottomDialog = rememberBottomDialogState()

    LaunchedEffect("effect"){
        viewModel.effect.onEach {
            when(it){
                is BleListContract.Effect.Navigation -> onNavigationEvent(it)
                is BleListContract.Effect.HideFilter -> launch {
                    bottomDialog.hide()
                }
                is BleListContract.Effect.ShowFilter -> launch {
                    bottomDialog.show {
                        Filter(
                            filter = viewModel.viewState.value.bleFilter,
                            onEvent = {
                                viewModel.setEvent(it)
                            }
                        )
                    }
                }
            }
        }.launchIn(this)
    }

    Column {

        TopAppBar(
            title = {
                Text(text = "Arma BLE")
            },
            actions = {

                Row(
                    modifier = Modifier
                        .padding(horizontal = 8.dp)
                        .align(Alignment.CenterVertically)
                ) {

                    Text(text = "${state.bleList.size}")
                    
                    Spacer(modifier = Modifier.width(12.dp))
                    
                    Text(text = "${state.bleList.filter { 
                        it.batteryLevel == 100 
                    }.filterNot { SystemClock.elapsedRealtime() - it.scanTime > 10_000 }.size}")

                    Text(text = " | ")

                    Text(
                        text = "${state.bleList.filter { SystemClock.elapsedRealtime() - it.scanTime > 10_000 }.size}",
                        color = LocalContentColor.current.copy(alpha = ContentAlpha.disabled)
                    )

                    Text(text = " | ")

                    Text(
                        text = "${state.bleList.filter { it.batteryLevel < 100 }.size}",
                        color = MaterialTheme.colorScheme.error
                    )

                }

                IconButton(
                    onClick = {
                        viewModel.setEvent(BleListContract.Event.OnShowFilter)
                    }
                ) {

                    Icon(
                        imageVector = Icons.Rounded.FilterAlt,
                        contentDescription = null
                    )

                }

            }
        )

        val filteredData = remember(state.bleList, state.bleFilter) {

            state.bleList.filter {
                (it.type == state.bleFilter.bleType || state.bleFilter.bleType == null) &&
                        it.name.contains(state.bleFilter.name) &&
                        it.serial.contains(state.bleFilter.mac) &&
                        state.bleFilter.rssi.contains(it.rssi?.toFloat() ?: Float.MIN_VALUE) &&
                        state.bleFilter.battery.contains(it.batteryLevel.toFloat())
            }.let {
                when (state.bleFilter.sortField) {
                    BleFilter.Field.Name -> it.sortedBy { it.name }
                    BleFilter.Field.Mac -> it.sortedBy { it.serial }
                    BleFilter.Field.Distance -> it.sortedBy {
                        10.0.pow(
                            (it.tx.toDouble() - (it.rssi?.toDouble() ?: 0.0) - 74) / 20
                        ).toFloat()
                    }

                    BleFilter.Field.Dbm -> it.sortedBy { it.rssi ?: 0 }
                    BleFilter.Field.Battery -> it.sortedBy { it.batteryLevel }
                }
            }.let {

                when (state.bleFilter.sortOrder) {
                    BleFilter.Order.Asc -> it
                    BleFilter.Order.Desc -> it.reversed()
                }

            }

        }

        if(filteredData.isEmpty()){
            LinearProgressIndicator(
                strokeCap = StrokeCap.Round,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(3.dp)
            )
        }

        if(filteredData.isEmpty()){

            Box(modifier = Modifier.fillMaxSize()){
                Text(
                    modifier = Modifier.align(Alignment.Center),
                    style = MaterialTheme.typography.titleMedium,
                    text = "Метки в области не найдены"
                )
            }

        } else {
            LazyColumn(
                verticalArrangement = Arrangement.spacedBy(8.dp),
                modifier = Modifier.fillMaxSize()
            ) {

                items(items = state.connectedBleList){

                    ConnectedBleItem(ble = it) {
                        viewModel.setEvent(BleListContract.Event.OnConnectToBle(it.serial))
                    }

                }



                items(items = filteredData) {

                    BleItem(
                        ble = it,
                        onClick = {
                            viewModel.setEvent(BleListContract.Event.OnConnectToBle(it.serial))
                        }
                    )

                }

            }
        }

    }

}

@Composable
fun ItemIcon(
    image: @Composable BoxScope.() -> Unit
){

    Surface(
        modifier = Modifier.size(40.dp),
        color = MaterialTheme.colorScheme.surfaceVariant,
        shape = CircleShape
    ) {
        Box(modifier = Modifier.fillMaxSize()) {

            image()

        }
    }

}

private fun Int.toSignalLevel(): Int {
    return when(this){
        in -30 downTo -52 -> 4
        in -51 downTo -63 -> 3
        in -62 downTo -75 -> 2
        in -74 downTo -89 -> 1
        else -> 0
    }
}

@Composable
fun BleItem(
    ble: BleInfo,
    onClick: () -> Unit
){

    val color = if(ble.batteryLevel < 100){
        MaterialTheme.colorScheme.errorContainer
    } else {
        MaterialTheme.colorScheme.background
    }

    val highAlpha = ContentAlpha.high
    val disabledAlpha = ContentAlpha.disabled


    var time by remember {
        mutableLongStateOf(
            SystemClock.elapsedRealtime()
        )
    }

    LaunchedEffect(ble.scanTime) {
        while(true) {
            time = SystemClock.elapsedRealtime()
            delay(100)
        }
    }

    var alpha = if(SystemClock.elapsedRealtime() - ble.scanTime > 10_000){
        disabledAlpha
    } else {
        highAlpha
    }


    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(16.dp))
            .background(color)
            .clickable { onClick() }
            .padding(vertical = 8.dp, horizontal = 16.dp)
            .alpha(alpha)

    ) {

        Box {

            ItemIcon {
                Icon(
                    modifier = Modifier.align(Alignment.Center),
                    imageVector = ble.type.icon,
                    contentDescription = null
                )
            }

            if(ble.tableStatus !== BleInfo.HistoryTableStatus.DISABLED){

                Surface(
                    shape = CircleShape,
                    color = color,
                    modifier = Modifier.align(Alignment.TopEnd)
                ) {

                    Surface(
                        shape = CircleShape,
                        color = when(ble.tableStatus){
                            BleInfo.HistoryTableStatus.EMPTY -> Color(0xff009116)
                            BleInfo.HistoryTableStatus.NOT_EMPTY -> MaterialTheme.colorScheme.error
                            else -> Color.Transparent
                        },
                        modifier = Modifier
                            .size(12.dp)
                            .padding(2.dp)
                    ) {

                    }

                }

            }

        }

        Column {

            Text(text = ble.name)

            Text(
                style = MaterialTheme.typography.bodyMedium,
                text = ble.serial
            )

            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.alpha(0.7f)
            ) {

                Icon(
                    modifier = Modifier.size(16.dp),
                    imageVector = Icons.Rounded.CompareArrows,
                    contentDescription = null
                )

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

                Text(
                    style = MaterialTheme.typography.bodyMedium,
                    text = String.format("%.3f", (10.0.pow((ble.tx.toDouble() - (ble.rssi?.toDouble() ?: 0.0) - 74) / 20))) + " м."
                )

            }

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

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.alpha(0.7f)
                ) {

                    SignalLevel(level = ble.rssi?.toSignalLevel() ?: 0)

                    Spacer(modifier = Modifier.width(4.dp))
                    
                    Box {

                        Text(
                            style = MaterialTheme.typography.bodyMedium,
                            text = "-999 dBm",
                            modifier = Modifier.alpha(0f)
                        )

                        Text(
                            style = MaterialTheme.typography.bodyMedium,
                            text = ble.rssi.toString() + " dBm"
                        )

                    }

                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.alpha(0.7f)
                ) {

                    val color = if(ble.batteryLevel < 100){
                        MaterialTheme.colorScheme.error
                    } else {
                        LocalContentColor.current
                    }

                    Icon(
                        modifier = Modifier.size(16.dp),
                        imageVector = Icons.Rounded.BatteryFull,
                        contentDescription = null,
                        tint = color
                    )

                    Box {

                        Text(
                            style = MaterialTheme.typography.bodyMedium,
                            text = "100 %",
                            modifier = Modifier.alpha(0f)
                        )

                        Text(
                            style = MaterialTheme.typography.bodyMedium,
                            text = ble.batteryLevel.toString() + " %",
                            color = color
                        )

                    }


                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.alpha(0.7f)
                ) {

                    Icon(
                        modifier = Modifier.size(16.dp),
                        imageVector = Icons.Rounded.ArrowRightAlt,
                        contentDescription = null
                    )

                    Box {

                        Text(
                            style = MaterialTheme.typography.bodyMedium,
                            text = "99s",
                            modifier = Modifier.alpha(0f)
                        )

                        Text(
                            style = MaterialTheme.typography.bodyMedium,
                            text = ">1m",
                            modifier = Modifier.alpha(0f)
                        )

                        val lastAdv = ((time - ble.scanTime) / 1_000)

                        Text(
                            style = MaterialTheme.typography.bodyMedium,
                            text = if(lastAdv > 60){
                                ">1m"
                            } else {
                                "${lastAdv}s"
                            }
                        )

                    }


                }


            }

        }

    }

}

@Composable
private fun ConnectedBleItem(
    ble: ConnectedBleInfo,
    onClick: () -> Unit
){

    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(16.dp))
            .clickable { onClick() }
            .background(MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = .99f))
            .padding(vertical = 8.dp, horizontal = 16.dp)

    ) {

        ItemIcon {
            Icon(
                modifier = Modifier.align(Alignment.Center),
                imageVector = Icons.Rounded.Link,
                contentDescription = null
            )
        }

        Column {

            Text(text = ble.name)

            Text(
                style = MaterialTheme.typography.bodyMedium,
                text = ble.serial
            )

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

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.alpha(0.7f)
                ) {

                    Text(
                        style = MaterialTheme.typography.bodyMedium,
                        text = "Соединено"
                    )

                }
            }

        }

    }

}