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

import androidx.compose.foundation.background
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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.BatteryFull
import androidx.compose.material.icons.rounded.Bluetooth
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.Info
import androidx.compose.material.icons.rounded.Nfc
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.ShortText
import androidx.compose.material.icons.rounded.SignalCellularAlt
import androidx.compose.material.icons.rounded.Sort
import androidx.compose.material.icons.rounded.SortByAlpha
import androidx.compose.material.icons.rounded.Speed
import androidx.compose.material.icons.rounded.Thermostat
import androidx.compose.material.icons.rounded.Warning
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RangeSlider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import llc.arma.ble.domain.model.BleFilter
import llc.arma.ble.domain.model.BleInfo

val BleFilter.Order.localized: String
    get() {
        return when(this){
            BleFilter.Order.Asc -> "Прямой ↓"
            BleFilter.Order.Desc -> "Обратный ↑"
        }
    }

val BleFilter.Field.localized: String
    get() {
        return when(this){
            BleFilter.Field.Name -> "Имя"
            BleFilter.Field.Mac -> "MAC"
            BleFilter.Field.Distance -> "Расстояние"
            BleFilter.Field.Dbm -> "dBm"
            BleFilter.Field.Battery -> "Заряд"
        }
    }

val BleInfo.Type?.localized: String
    get() {
        return when(this){
            BleInfo.Type.HOST -> "Хост"
            BleInfo.Type.BEACON -> "Маяк"
            BleInfo.Type.THERMOMETER -> "Термодатчик"
            BleInfo.Type.ACCELEROMETER -> "Акселерометр"
            null -> "Все"
        }
    }

val BleInfo.Type?.icon: ImageVector
    get() {
        return when(this){
            BleInfo.Type.BEACON -> Icons.Rounded.Nfc
            BleInfo.Type.THERMOMETER -> Icons.Rounded.Thermostat
            BleInfo.Type.ACCELEROMETER -> Icons.Rounded.Speed
            BleInfo.Type.HOST -> Icons.Rounded.Info
            else -> Icons.Rounded.Warning
        }
    }

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Filter(
    filter: BleFilter,
    onEvent: (BleListContract.Event) -> Unit
) {

    Column(

    ) {

        Text(
            modifier = Modifier.padding(horizontal = 12.dp),
            text = "Фильтр",
            style = MaterialTheme.typography.titleLarge
        )

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

        Column(
            modifier = Modifier
                .padding(horizontal = 12.dp)
                .verticalScroll(rememberScrollState())
        ) {

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

            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {

                Icon(
                    imageVector = Icons.Rounded.Sort,
                    contentDescription = null,
                    modifier = Modifier.padding(12.dp)
                )

                var expanded by remember { mutableStateOf(false) }

                ExposedDropdownMenuBox(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(end = 8.dp),
                    expanded = expanded,
                    onExpandedChange = {
                        expanded = it
                    }
                ) {

                    OutlinedTextField(
                        modifier = Modifier
                            .menuAnchor()
                            .fillMaxWidth(),
                        readOnly = true,
                        value = filter.sortField.localized,
                        onValueChange = { },
                        label = { Text("Сортировка") },
                        trailingIcon = {
                            ExposedDropdownMenuDefaults.TrailingIcon(
                                expanded = expanded
                            )
                        }
                    )

                    ExposedDropdownMenu(
                        modifier = Modifier
                            .background(MaterialTheme.colorScheme.background)
                            .fillMaxWidth(),
                        expanded = expanded,
                        onDismissRequest = {
                            expanded = false
                        }
                    ) {

                        BleFilter.Field.entries.forEach { selectionOption ->
                            DropdownMenuItem(
                                onClick = {
                                    onEvent(
                                        BleListContract.Event.OnSortFieldChanged(
                                            selectionOption
                                        )
                                    )
                                    expanded = false
                                },
                                text = {
                                    Text(text = selectionOption.localized)
                                }
                            )
                        }
                    }
                }

            }

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

            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {

                Icon(
                    imageVector = Icons.Rounded.SortByAlpha,
                    contentDescription = null,
                    modifier = Modifier.padding(12.dp)
                )

                var expanded by remember { mutableStateOf(false) }

                ExposedDropdownMenuBox(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(end = 8.dp),
                    expanded = expanded,
                    onExpandedChange = {
                        expanded = it
                    }
                ) {

                    OutlinedTextField(
                        modifier = Modifier
                            .menuAnchor()
                            .fillMaxWidth(),
                        readOnly = true,
                        value = filter.sortOrder.localized,
                        onValueChange = { },
                        label = { Text("Напрвление сортировки") },
                        trailingIcon = {
                            ExposedDropdownMenuDefaults.TrailingIcon(
                                expanded = expanded
                            )
                        }
                    )

                    ExposedDropdownMenu(
                        modifier = Modifier
                            .background(MaterialTheme.colorScheme.background)
                            .fillMaxWidth(),
                        expanded = expanded,
                        onDismissRequest = {
                            expanded = false
                        }
                    ) {

                        BleFilter.Order.entries.forEach { selectionOption ->
                            DropdownMenuItem(
                                onClick = {
                                    onEvent(
                                        BleListContract.Event.OnSortOrderChanged(
                                            selectionOption
                                        )
                                    )
                                    expanded = false
                                },
                                text = {
                                    Text(text = selectionOption.localized)
                                }
                            )
                        }
                    }
                }

            }

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

            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {

                Icon(
                    imageVector = Icons.Rounded.Bluetooth,
                    contentDescription = null,
                    modifier = Modifier.padding(12.dp)
                )

                var expanded by remember { mutableStateOf(false) }

                ExposedDropdownMenuBox(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(end = 8.dp),
                    expanded = expanded,
                    onExpandedChange = {
                        expanded = it
                    }
                ) {

                    OutlinedTextField(
                        modifier = Modifier
                            .menuAnchor()
                            .fillMaxWidth(),
                        readOnly = true,
                        value = filter.bleType.localized,
                        onValueChange = { },
                        label = { Text("Тип") },
                        trailingIcon = {
                            ExposedDropdownMenuDefaults.TrailingIcon(
                                expanded = expanded
                            )
                        }
                    )

                    ExposedDropdownMenu(
                        modifier = Modifier
                            .background(MaterialTheme.colorScheme.background)
                            .fillMaxWidth(),
                        expanded = expanded,
                        onDismissRequest = {
                            expanded = false
                        }
                    ) {

                        mutableListOf<BleInfo.Type?>(null).apply {
                            addAll(BleInfo.Type.entries.toTypedArray())
                        }.forEach { selectionOption ->
                            DropdownMenuItem(
                                onClick = {
                                    onEvent(
                                        BleListContract.Event.OnTypeChanged(
                                            selectionOption
                                        )
                                    )
                                    expanded = false
                                },
                                text = {
                                    Text(text = selectionOption.localized)
                                }
                            )
                        }
                    }
                }

            }

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

            Row(
                verticalAlignment = Alignment.CenterVertically
            ){

                Icon(
                    imageVector = Icons.Rounded.Search,
                    contentDescription = null,
                    modifier = Modifier.padding(12.dp)
                )

                OutlinedTextField(
                    value = filter.name,
                    singleLine = true,
                    onValueChange = {
                        onEvent(BleListContract.Event.OnNameFilterChanged(it))
                    },
                    label = {
                        Text(text = "Имя")
                    },
                    trailingIcon = {

                        if(filter.name.isNotEmpty()) {

                            IconButton(
                                onClick = { onEvent(BleListContract.Event.OnNameFilterChanged("")) }
                            ) {
                                Icon(
                                    imageVector = Icons.Rounded.Close,
                                    contentDescription = null
                                )
                            }

                        }

                    },
                    modifier = Modifier
                        .padding(end = 8.dp)
                        .fillMaxWidth()

                )

            }

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

            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {

                Icon(
                    imageVector = Icons.Rounded.ShortText,
                    contentDescription = null,
                    modifier = Modifier.padding(12.dp)
                )

                OutlinedTextField(
                    value = filter.mac,
                    singleLine = true,
                    onValueChange = {
                        onEvent(BleListContract.Event.OnMacFilterChanged(it))
                    },
                    label = {
                        Text(text = "Mac")
                    },
                    trailingIcon = {

                        if (filter.mac.isNotEmpty()) {

                            IconButton(
                                onClick = { onEvent(BleListContract.Event.OnMacFilterChanged("")) }
                            ) {
                                Icon(
                                    imageVector = Icons.Rounded.Close,
                                    contentDescription = null
                                )
                            }

                        }

                    },
                    modifier = Modifier
                        .padding(end = 8.dp)
                        .fillMaxWidth()
                )

            }

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

            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(end = 8.dp)
            ) {

                Icon(
                    imageVector = Icons.Rounded.SignalCellularAlt,
                    contentDescription = null,
                    modifier = Modifier.padding(12.dp)
                )

                Column() {

                    RangeSlider(
                        value = filter.rssi,
                        onValueChange = {
                            onEvent(BleListContract.Event.OnRssiRangeChanged(it))
                        },
                        valueRange = (-100f)..(-10f),
                        steps = 89,
                        colors = SliderDefaults.colors(
                            activeTickColor = MaterialTheme.colorScheme.primary,
                            inactiveTickColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.38f)
                        )
                    )

                    Row() {

                        Text(text = filter.rssi.start.toInt().toString() + " dBm")

                        Spacer(modifier = Modifier.weight(1f))

                        Text(text = filter.rssi.endInclusive.toInt().toString() + " dBm")

                    }

                }

            }

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

            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(end = 8.dp)
            ) {

                Icon(
                    imageVector = Icons.Rounded.BatteryFull,
                    contentDescription = null,
                    modifier = Modifier.padding(12.dp)
                )

                Column() {

                    RangeSlider(
                        value = filter.battery,
                        onValueChange = {
                            onEvent(BleListContract.Event.OnBatteryRangeChanged(it))
                        },
                        valueRange = 0f..100f,
                        steps = 99,
                        colors = SliderDefaults.colors(
                            activeTickColor = MaterialTheme.colorScheme.primary,
                            inactiveTickColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.38f)
                        )
                    )

                    Row {

                        Text(text = "0 %")

                        Spacer(modifier = Modifier.weight(1f))

                        Text(text = "100 %")

                    }

                }

            }

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

            Box(
                modifier = Modifier
            ) {

                Surface(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp),
                    shape = CircleShape,
                    color = MaterialTheme.colorScheme.primaryContainer,
                    onClick = {
                        onEvent(BleListContract.Event.OnHideFilter)
                    }
                ) {

                    Box(modifier = Modifier.fillMaxSize()) {

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

                    }

                }

            }

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

            Box(
                modifier = Modifier
            ) {

                Surface(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp),
                    shape = CircleShape,
                    color = MaterialTheme.colorScheme.secondaryContainer,
                    onClick = {
                        onEvent(BleListContract.Event.OnResetFilter)
                    }
                ) {

                    Box(modifier = Modifier.fillMaxSize()) {

                        Text(
                            modifier = Modifier.align(Alignment.Center),
                            color = MaterialTheme.colorScheme.onSecondaryContainer,
                            style = MaterialTheme.typography.labelLarge,
                            text = "Сбросить"
                        )

                    }

                }
            }

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

        }

    }

}