package com.laseroptek.raman.ui.screens.config

import android.content.res.Configuration
import android.media.AudioManager
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.laseroptek.raman.R
import com.laseroptek.raman.const.CMD
import com.laseroptek.raman.const.READ_WRITE
import com.laseroptek.raman.data.datasource.db.RamanDatabase
import com.laseroptek.raman.data.model.serial.GuideBeam
import com.laseroptek.raman.data.source.db.RamanDatabaseService
import com.laseroptek.raman.repository.DatabaseRepository
import com.laseroptek.raman.repository.PreferenceRepository
import com.laseroptek.raman.repository.SerialPortRepository
import com.laseroptek.raman.ui.screens.main.MainViewModel
import com.laseroptek.raman.ui.theme.RobotoTypography
import com.laseroptek.raman.utils.DefaultDispatcherProvider
import com.laseroptek.raman.utils.SystemSound
import com.laseroptek.raman.utils.SystemSound.setCurrentSystemVolume
import com.laseroptek.raman.utils.ext.dropShadow
import com.laseroptek.raman.utils.ext.noRippleClickable
import com.laseroptek.raman.utils.ext.px
import com.laseroptek.raman.utils.slider.LabeledRangeSlider
import kotlinx.coroutines.launch
import timber.log.Timber
import kotlin.math.roundToInt

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ConfigScreen(
    mainNavController: NavHostController = rememberNavController(),
    paddingValues: PaddingValues = PaddingValues(),
    mainViewModel: MainViewModel = hiltViewModel<MainViewModel>(),
    configViewModel: ConfigViewModel = hiltViewModel<ConfigViewModel>()
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    val pulseType by mainViewModel.pulseType.collectAsState()
    val guideBeam by mainViewModel.guideBeam.collectAsState()
    val guideBeamMax by mainViewModel.guideBeamMax.collectAsState()
    val guideBeamMin by mainViewModel.guideBeamMin.collectAsState()

    val currentSystemVolume = SystemSound.getCurrentSystemVolume(context, AudioManager.STREAM_MUSIC)
    val maxSystemVolume = SystemSound.getMaximumVolumeForStream(context, AudioManager.STREAM_MUSIC)    //getMaxSystemVolume(context, AudioManager.STREAM_SYSTEM)

    val sliderVolume by mainViewModel.sliderVolume.collectAsState()
    val prevSliderVolume by configViewModel.prevSliderVolume.collectAsState()

    LaunchedEffect(Unit) {
        Timber.d("LaunchedEffect - ConfigScreen")

        // set slider volume from system volume
        val sliderVolume = currentSystemVolume.coerceIn(0, 10)
            //mapSystemVolumeToSliderPosition(currentSystemVolume, maxSystemVolume)
        Timber.d("sliderVolume is: $sliderVolume")
        //mainViewModel.setSliderVolume(sliderVolume.toFloat())
    }

    DisposableEffect(Unit) {
        onDispose {
            Timber.d("MyComposable is being disposed!")
            //keyboardController?.hide()
            //focusManager.clearFocus(force = true) // Hide the keyboard
        }
    }

    Box {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(
                    start = 130.px.dp,
                    end = 30.px.dp,
                    top = 30.px.dp,
                    bottom = 30.px.dp
                ),
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            // 1. Top - Engineer Mode Popup
            // Engineer Mode
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(50.px.dp),
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.Top
            ) {
                TextButton(
                    modifier = Modifier
                        .size(156.px.dp, 44.px.dp)
                        .clip(RoundedCornerShape(100.px.dp))
                        .background(Color(35, 35, 33))
                        .shadow(
                            elevation = 1.px.dp,
                            shape = RoundedCornerShape(100.px.dp),
                            ambientColor = Color(0, 0, 0).copy(alpha = 0.1f),
                            spotColor = Color(0, 0, 0).copy(alpha = 0.2f),
                            clip = true
                        ),
                    onClick = {
                        mainViewModel.showEngineerPasswordPopup = true
                    }
                ) {
                    Text(
                        text = stringResource(R.string.engineer_mode),
                        style = RobotoTypography.bodyMedium.copy(
                            fontSize = 16.px.sp,
                            fontWeight = FontWeight.Medium,
                            lineHeight = 24.px.sp,
                        ),
                        textAlign = TextAlign.Center,
                        color = Color(243,205,81)
                    )
                }
            }

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

            // 2. Middle - Trigger and Pulse Type Setting
            Row(modifier = Modifier
                .fillMaxWidth()
                .height(100.px.dp),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ){
                val unSelectedBackground = Brush.verticalGradient(
                    colors = listOf(
                        Color(230, 230, 230).copy(alpha = 0.98f),
                        Color(200, 200, 200),
                    )
                )
                val selectedBackGround = Color(47, 51, 57)

                // Trigger Type
                /*
                Column(
                    modifier = Modifier
                        .size(268.px.dp, 100.px.dp)
                ) {
                    // Trigger Type - Text
                    Row(modifier = Modifier
                        .size(268.px.dp, 30.px.dp)
                    ) {
                        Text(
                            text = stringResource(R.string.trigger_type),
                            textAlign = TextAlign.Start,
                            modifier = Modifier.fillMaxWidth(),
                            style = RobotoTypography.bodyMedium.copy(
                                color = Color.Black,
                                fontSize = 20.px.sp,
                                fontWeight = FontWeight.Normal,
                            )
                        )
                    }

                    Spacer(modifier = Modifier.height(10.px.dp))

                    // Finger S/W and Foot S/W
                    Row(
                        modifier = Modifier
                            .size(268.px.dp, 50.px.dp)
                    ) {
                        // Finger S/W
                        TextButton(
                            modifier = Modifier
                                .size(width = 134.px.dp, height = 50.px.dp)
                                .clip(
                                    RoundedCornerShape(
                                        topStart = 10.px.dp,
                                        bottomStart = 10.px.dp
                                    )
                                )
                                .background(
                                    Brush.verticalGradient(
                                        colors = listOf(
                                            Color(250, 250, 250).copy(alpha = 0.98f),
                                            Color(218, 218, 218),
                                        )
                                    ),
                                    shape = RoundedCornerShape(
                                        topStart = 10.px.dp,
                                        bottomStart = 10.px.dp
                                    )
                                ),
                            onClick = {
                                Timber.d("Finger S/W clicked")
                            }
                        ) {
                            Text(
                                text = stringResource(R.string.finger_sw),
                                textAlign = TextAlign.Center,
                                modifier = Modifier.fillMaxWidth(),
                                style = RobotoTypography.bodyMedium.copy(
                                    color = Color.Black,
                                    fontSize = 16.px.sp,
                                )
                            )
                        }

                        // Foot S/W
                        TextButton(
                            modifier = Modifier
                                .size(width = 134.px.dp, height = 50.px.dp)
                                .clip(
                                    RoundedCornerShape(
                                        topEnd = 10.px.dp,
                                        bottomEnd = 10.px.dp
                                    )
                                )
                                .background(
                                    color = Color(47, 51, 57),
                                    shape = RoundedCornerShape(
                                        topEnd = 10.px.dp,
                                        bottomEnd = 10.px.dp
                                    )
                                ),
                            onClick = {
                                Timber.d("Foot S/W clicked")
                            }
                        ) {
                            Text(
                                text = stringResource(R.string.foot_sw),
                                textAlign = TextAlign.Center,
                                modifier = Modifier.fillMaxWidth(),
                                style = RobotoTypography.bodyMedium.copy(
                                    color = Color.White,
                                    fontSize = 16.px.sp,
                                )
                            )
                        }
                    }
                }

                Spacer(modifier = Modifier.weight(2f))
                */

                // Pulse Type
                Column(
                    modifier = Modifier
                        .size(268.px.dp, 100.px.dp)
                ) {
                    // Pulse Type - Text
                    Row(modifier = Modifier
                        .size(268.px.dp, 30.px.dp)
                    ) {
                        Text(
                            text = stringResource(R.string.pulse_type),
                            textAlign = TextAlign.Start,
                            modifier = Modifier.fillMaxWidth(),
                            style = RobotoTypography.bodyMedium.copy(
                                color = Color.Black,
                                fontSize = 20.px.sp,
                                fontWeight = FontWeight.Normal
                            )
                        )
                    }

                    Spacer(modifier = Modifier.height(10.px.dp))

                    // Single and Repeat
                    Row(
                        modifier = Modifier
                            .size(268.px.dp, 50.px.dp)
                    ) {
                        // Single
                        TextButton(
                            modifier = Modifier
                                .size(width = 134.px.dp, height = 50.px.dp)
                                .clip(
                                    RoundedCornerShape(
                                        topStart = 10.px.dp,
                                        bottomStart = 10.px.dp
                                    )
                                )
                                .background(
                                    if (pulseType == 0)
                                        SolidColor(selectedBackGround)
                                    else unSelectedBackground,
                                ),
                            onClick = {
                                Timber.d("Single clicked")
                                mainViewModel.setPulseType(0)
                            }
                        ) {
                            Text(
                                text = stringResource(R.string.single),
                                textAlign = TextAlign.Center,
                                modifier = Modifier.fillMaxWidth(),
                                style = RobotoTypography.bodyMedium.copy(
                                    color = if (pulseType ==0) Color.White else Color.Black,
                                    fontSize = 16.px.sp,
                                )
                            )
                        }

                        // Repeat
                        TextButton(
                            modifier = Modifier
                                .size(width = 134.px.dp, height = 50.px.dp)
                                .clip(
                                    RoundedCornerShape(
                                        topEnd = 10.px.dp,
                                        bottomEnd = 10.px.dp
                                    )
                                )
                                .background(
                                    if (pulseType == 1) SolidColor(selectedBackGround) else unSelectedBackground,
                                    shape = RoundedCornerShape(
                                        topEnd = 10.px.dp,
                                        bottomEnd = 10.px.dp
                                    )
                                ),
                            onClick = {
                                Timber.d("Repeat clicked")
                                mainViewModel.setPulseType(1)
                            }
                        ) {
                            Text(
                                text = stringResource(R.string.repeat),
                                textAlign = TextAlign.Center,
                                modifier = Modifier.fillMaxWidth(),
                                style = RobotoTypography.bodyMedium.copy(
                                    color = if (pulseType == 1) Color.White else Color.Black,
                                    fontSize = 16.px.sp,
                                )
                            )
                        }
                    }
                }

                Spacer(modifier = Modifier.weight(3f))
            }

            Spacer(modifier = Modifier.height(67.px.dp))

            // 3. Low - Gudide Beam & Volume Settings
            Row(modifier = Modifier
                .fillMaxWidth()
                .height(140.px.dp),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ){
                Column(modifier = Modifier
                    .size(470.px.dp, 140.px.dp)
                    .clip(RoundedCornerShape(24.px.dp))
                ) {
                    // Guide Beam
                    Text(
                        text = stringResource(R.string.guide_beam),
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        style = RobotoTypography.bodyMedium.copy(
                            fontSize = 20.px.sp,
                            fontWeight = FontWeight.Normal,
                            lineHeight = 24.px.sp
                        ),
                        textAlign = TextAlign.Start,
                        color = Color.Black
                    )

                    // Guide Beam Slider & Value(Text)
                    Row(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        // Guide Beam Slider
                        //val value = sliderPositionGuideBeam.value.toInt()
                        val steps = (0..10).step(1).toList()
                        //var upperBound by rememberSaveable { mutableStateOf(steps[value]) }	// steps[steps.size - 1]
                        //var upperBound = 10

                        LabeledRangeSlider(
                            selectedUpperBound = guideBeam.toInt(),
                            steps = steps,
                            onRangeChanged = { upper ->
                                // LIVE update for visual feedback of the slider thumb
                                mainViewModel.setGuideBeam(upper.toFloat())
                                Timber.d("GuideBeam onRangeChanged: $upper")
                            },
                            onRangeChangeFinished = { finalUpper ->
                                //upperBound = upper
                                //mainViewModel.setGuideBeam(finalUpper.toFloat())
                                scope.launch {
                                    mainViewModel.saveGuideBeamToPreference()
                                }

                                /*
                                val value = when(guideBeam.toInt()) {
                                    0 -> 0
                                    1 -> guideBeamMin
                                    10 -> guideBeamMax
                                    else -> (guideBeamMin + (guideBeam.toInt() - 1) * ((guideBeamMax - guideBeamMin) / 9))
                                }
                                */
                                val value = (guideBeamMin + (guideBeam.toInt() - 1) * ((guideBeamMax - guideBeamMin) / 9))

                                Timber.d("guideBeam: $value, guideBeamMax: $guideBeamMax, guideBeamMin: $guideBeamMin")
                                mainViewModel.txPacket(READ_WRITE.WRITE, CMD.GUIDE_BEAM, GuideBeam(value = value))
                                Timber.d("Updated selected range ${steps[0]..finalUpper}")
                            },
                            modifier = Modifier
                                .fillMaxHeight()
                                .width(260.px.dp)
                                .padding(start = 16.dp, end = 16.dp)
                        )

                        Spacer(Modifier.weight(1f))

                        // ValueBox
                        Column(
                            modifier = Modifier
                                .size(93.px.dp, 50.px.dp)
                                .background(
                                    Brush.verticalGradient(
                                        colors = listOf(
                                            Color(255, 255, 255),
                                            Color(250, 250, 250),
                                        )
                                    ),
                                    shape = RoundedCornerShape(12.px.dp)
                                )
                                .border(
                                    width = 1.px.dp,
                                    color = Color(209, 209, 209),
                                    shape = RoundedCornerShape(12.px.dp)
                                )
                            , horizontalAlignment = Alignment.CenterHorizontally
                            , verticalArrangement = Arrangement.Center
                        ) {
                            Text(
                                text = "${guideBeam.toInt()}",
                                style = RobotoTypography.bodyMedium.copy(
                                    fontSize = 24.px.sp,
                                    fontWeight = FontWeight.Medium,
                                    lineHeight = 32.px.sp,
                                ),
                                textAlign = TextAlign.Center,
                                color = Color.Black,
                            )
                        }

                        Spacer(Modifier.weight(1f))
                    }
                }

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

                Column(modifier = Modifier
                    .size(520.px.dp, 140.px.dp)
                    .clip(RoundedCornerShape(24.px.dp)),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.Start
                ) {
                    // Volume
                    Text(
                        text = stringResource(R.string.volume),
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        style = RobotoTypography.bodyMedium.copy(
                            fontSize = 20.px.sp,
                            fontWeight = FontWeight.Medium,
                            lineHeight = 24.px.sp,
                        ),
                        textAlign = TextAlign.Start,
                        color = Color.Black
                    )

                    // Volume Slider & Value(Text)
                    Row(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(16.dp)
                        , verticalAlignment = Alignment.CenterVertically
                        , horizontalArrangement = Arrangement.Center
                    ) {
                        val steps = (0..10.toInt()).step(1).toList()
                        LabeledRangeSlider(
                            selectedUpperBound = sliderVolume.toInt(), //sliderPositionVolume.value.toInt(),
                            steps = steps,
                            onRangeChanged = { upper ->
                                mainViewModel.setSliderVolume(upper.toFloat())
                                scope.launch {
                                    mainViewModel.saveSliderVolumeToPreference()
                                }
                                Timber.d("Volume onRangeChanged: $upper")
                            },
                            onRangeChangeFinished = { finalUpper ->
                                val finalSystemVolume = mapSliderPositionToSystemVolume(finalUpper.toInt(), maxSystemVolume)
                                setCurrentSystemVolume(
                                    context,
                                    AudioManager.STREAM_MUSIC,  //AudioManager.STREAM_SYSTEM,
                                    finalSystemVolume
                                )
                                scope.launch {
                                    mainViewModel.playBeepSound()
                                }
                                Timber.d("Updated selected range ${steps[0]..sliderVolume.toInt()}")

                            },
                            modifier = Modifier
                                .width(260.px.dp)
                                .padding(start = 16.dp, end = 16.dp)
                        )

                        Spacer(Modifier.weight(1f))

                        // ValueBox
                        Column(
                            modifier = Modifier
                                .size(93.px.dp, 50.px.dp)
                                .background(
                                    Brush.verticalGradient(
                                        colors = listOf(
                                            Color(255, 255, 255),
                                            Color(250, 250, 250),
                                        )
                                    ),
                                    shape = RoundedCornerShape(12.px.dp)
                                )
                                .border(
                                    width = 1.px.dp,
                                    color = Color(209, 209, 209),
                                    shape = RoundedCornerShape(12.px.dp)
                                )
                            , horizontalAlignment = Alignment.CenterHorizontally
                            , verticalArrangement = Arrangement.Center
                        ) {
                            Text(
                                text = "${sliderVolume.toInt()}",
                                style = RobotoTypography.bodyMedium.copy(
                                    fontSize = 24.px.sp,
                                    fontWeight = FontWeight.Medium,
                                    lineHeight = 32.px.sp,
                                ),
                                textAlign = TextAlign.Center,
                                color = Color.Black
                            )
                        }

                        Spacer(Modifier.weight(1f))

                        // icon
                        IconButton(
                            onClick = {
                                if (sliderVolume > 0f) {
                                    // UnMute -> Mute State
                                    configViewModel.setPrevSliderVolume( sliderVolume )
                                    mainViewModel.setSliderVolume(0f)
                                    scope.launch {
                                        mainViewModel.saveSliderVolumeToPreference()
                                    }
                                    setCurrentSystemVolume(context, AudioManager.STREAM_MUSIC, 0) // Also set system volume
                                    Timber.d("UnMute> sliderPositionVolume: ${sliderVolume}")
                                } else if (prevSliderVolume.toInt() == 0) {
                                    // Mute -> UnMute State
                                    configViewModel.setPrevSliderVolume( 1f )
                                    mainViewModel.setSliderVolume(1f)
                                    scope.launch {
                                        mainViewModel.saveSliderVolumeToPreference()
                                    }
                                    setCurrentSystemVolume(context, AudioManager.STREAM_MUSIC, 1)
                                    Timber.d("Mute> sliderPositionVolume: 1")
                                } else {
                                    // Mute -> UnMute State
                                    mainViewModel.setSliderVolume( prevSliderVolume )
                                    scope.launch {
                                        mainViewModel.saveSliderVolumeToPreference()
                                    }
                                    setCurrentSystemVolume(context, AudioManager.STREAM_MUSIC, prevSliderVolume.toInt())
                                    Timber.d("Mute> sliderPositionVolume: ${sliderVolume}")
                                }

                                scope.launch {
                                    mainViewModel.playBeepSound()
                                }

                            },
                            modifier = Modifier
                                .size(73.px.dp, 42.px.dp)
                                .clip(CircleShape)
                                .background(
                                    brush = Brush.linearGradient(
                                        colorStops = if (sliderVolume < 1f) {
                                            arrayOf(
                                                0.0f to Color(195, 195, 195),
                                                1.0f to Color(154, 155, 156),
                                            )
                                        } else {
                                            arrayOf(
                                                0.0f to Color(47, 51, 57),
                                                1.0f to Color(83, 88, 97),
                                            )
                                        }
                                    )
                                )
                                .border(
                                    1.px.dp,
                                    brush = Brush.linearGradient(
                                        colorStops = if (sliderVolume < 1f) {
                                            arrayOf(
                                                0.0f to Color(230, 230, 230),
                                                1.0f to Color(196, 196, 196),
                                            )
                                        } else {
                                            arrayOf(
                                                0.0f to Color(92, 99, 107),
                                                1.0f to Color(34, 37, 40),
                                            )
                                        }
                                    ),
                                    shape = CircleShape
                                )
                                .dropShadow(
                                    shape = CircleShape,
                                    color = Color(0, 0, 0).copy(alpha = 0.2f),
                                    blur = 53.05.px.dp,
                                    offsetY = 2.21.px.dp,
                                    offsetX = 0.px.dp,
                                    spread = 0.px.dp
                                )
                                .dropShadow(
                                    shape = CircleShape,
                                    color = Color(0, 0, 0).copy(alpha = 0.1f),
                                    blur = 6.63.px.dp,
                                    offsetY = 3.32.px.dp,
                                    offsetX = 0.px.dp,
                                    spread = 0.px.dp
                                ),
                        ) {
                            Image(
                                painter = painterResource(
                                    if (sliderVolume < 1f) {
                                        R.drawable.ic_speaker_off
                                    } else {
                                        R.drawable.ic_speaker_on
                                    }
                                ),
                                //painter = painterResource(R.drawable.ic_speaker_off),
                                contentDescription = null,
                                colorFilter = ColorFilter.tint(Color.White),
                                modifier = Modifier
                                    .size(20.px.dp),
                                contentScale = ContentScale.Crop,
                            )
                        }
                        Spacer(Modifier.weight(1f))
                    }
                }
                Spacer(modifier = Modifier.weight(1f))
            }

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

            // 4. Bottom - Time & Language Settings
            // Time Settings & Language
            Row(modifier = Modifier
                .fillMaxWidth()
                .height(100.px.dp),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ){
                // Time Setting
                ElevatedCard(
                    modifier = Modifier.padding(2.px.dp),
                    shape = RoundedCornerShape(45.px.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.px.dp),
                ) {
                    Row(
                        modifier = Modifier
                            .size(155.px.dp, 50.px.dp)
                            .noRippleClickable {
                                mainViewModel.showTimeSettingPopup = true
                            }
                        , horizontalArrangement = Arrangement.Center
                        , verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_clock),
                            contentDescription = null,
                            modifier = Modifier.size(15.px.dp),
                            contentScale = ContentScale.FillBounds,
                            colorFilter = ColorFilter.tint(Color.Black)
                        )
                        Spacer(modifier = Modifier.width(10.px.dp))
                        Text(
                            text = stringResource(R.string.time_setting),
                            style = RobotoTypography.bodyMedium.copy(
                                color = Color.Black,
                                fontSize = 14.px.sp,
                                lineHeight = 20.px.sp,
                            )
                        )
                    }
                }

                /*
                Spacer(Modifier.width(10.px.dp))

                // Language Button
                ElevatedCard(
                    modifier = Modifier.padding(2.px.dp),
                    shape = RoundedCornerShape(45.px.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.px.dp),
                ) {
                    Row(
                        modifier = Modifier
                            .size(155.px.dp, 50.px.dp)
                            .noRippleClickable {
                                mainViewModel.showLanguageScreen = true
                            }
                        , horizontalArrangement = Arrangement.Center
                        , verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_globe),
                            contentDescription = null,
                            modifier = Modifier.size(18.px.dp),
                            contentScale = ContentScale.FillBounds,
                            colorFilter = ColorFilter.tint(Color.Black)
                        )
                        Spacer(modifier = Modifier.width(10.px.dp))
                        Text(
                            text = stringResource(R.string.language),
                            style = RobotoTypography.bodyMedium.copy(
                                color = Color.Black,
                                fontSize = 14.px.sp,
                                lineHeight = 20.px.sp,
                            )
                        )
                    }
                }
                */

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

            Spacer(modifier = Modifier.weight(3f))
        }

        //////////////////////////////////////////////////////
        // Popups --> move to MainView
    }
}

private fun mapSystemVolumeToSliderPosition(currentSystemVolume: Int, maxSystemVolume: Int): Int {
    val maxSliderPosition = 10.0f

    if (currentSystemVolume < 0) return 0
    if (maxSystemVolume == 0) return 0 // Avoid division by zero

    // 1. Normalize the volume to a 0.0-1.0 scale
    val normalized = currentSystemVolume.toFloat() / maxSystemVolume.toFloat()

    // 2. Scale the normalized value to the slider's range (0.0-10.0)
    val scaledValue = normalized * maxSliderPosition

    // 3. Round to the nearest integer and return
    return scaledValue.roundToInt().coerceIn(0, 10)
}

private fun mapSliderPositionToSystemVolume(sliderPosition: Int, maxSystemVolume: Int): Int {
    val maxSliderPosition = 10.0f

    // 1. Normalize the slider position to a 0.0-1.0 scale
    val normalized = sliderPosition.toFloat() / maxSliderPosition

    // 2. Scale the normalized value to the system volume's range (0.0-15.0)
    val scaledValue = normalized * maxSystemVolume

    // 3. Round to the nearest integer, ensure it's within bounds, and return
    return scaledValue.roundToInt().coerceIn(0, 15)
}

@Preview(
    apiLevel = 34,
    uiMode = Configuration.UI_MODE_NIGHT_NO,
    showBackground = false,
    device = "spec:width=1920dp,height=1080dp,dpi=150,isRound=false,chinSize=0dp,orientation=landscape"
)
@Composable
fun PreviewConfigScreen(
    mainViewModel:MainViewModel = MainViewModel(
        preferenceRepository = PreferenceRepository(LocalContext.current),
        serialPortRepository = SerialPortRepository.createWithFakeRepository(),
        databaseRepository = DatabaseRepository(RamanDatabaseService(RamanDatabase.getInstance(LocalContext.current))),
        dispatcherProvider = DefaultDispatcherProvider(),
        applicationContext = LocalContext.current
    ),
    configViewModel:ConfigViewModel = ConfigViewModel(
        preferenceRepository = PreferenceRepository(LocalContext.current),
        serialPortRepository = SerialPortRepository.createWithFakeRepository(),
        databaseRepository = DatabaseRepository(RamanDatabaseService(RamanDatabase.getInstance(LocalContext.current))),
        dispatcherProvider = DefaultDispatcherProvider(),
        applicationContext = LocalContext.current
    )
) {
    ConfigScreen(
        mainViewModel = mainViewModel,
        configViewModel = configViewModel
    )
}