package com.laseroptek.raman.ui.screens.home.preset

import android.content.res.Configuration
import android.widget.Toast
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.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.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.VerticalDivider
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.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
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 com.laseroptek.raman.R
import com.laseroptek.raman.const.UpDownState
import com.laseroptek.raman.const.handPieceTypes
import com.laseroptek.raman.data.datasource.db.RamanDatabase
import com.laseroptek.raman.data.model.Preset
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.common.button.GradientImageButton
import com.laseroptek.raman.ui.common.fullscreen.FullScreen
import com.laseroptek.raman.ui.screens.main.MainViewModel
import com.laseroptek.raman.ui.theme.RobotoTypography
import com.laseroptek.raman.ui.theme.robotoTextStyle
import com.laseroptek.raman.utils.DefaultDispatcherProvider
import com.laseroptek.raman.utils.ext.dropShadow
import com.laseroptek.raman.utils.ext.innerShadow
import com.laseroptek.raman.utils.ext.noRippleClickable
import com.laseroptek.raman.utils.ext.px
import com.laseroptek.raman.utils.ext.simpleVerticalScrollbar
import kotlinx.coroutines.launch
import timber.log.Timber

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PresetLoadPopup(
    mainViewModel: MainViewModel = hiltViewModel<MainViewModel>(),
    presetViewModel: PresetViewModel = hiltViewModel<PresetViewModel>(),
    title: String = stringResource(R.string.load_title),
    onClick: (Boolean) -> Unit= {},
) {
    val scope = rememberCoroutineScope()

    var showDeleteConfirmDialog by remember { mutableStateOf(false) }

    val context = LocalContext.current
    val focusManager = LocalFocusManager.current

    val selectedPresetIndex by presetViewModel.selectedPresetIndex.collectAsState()
    val isEditMode by presetViewModel.isEditMode.collectAsState()
    val contentAlignment = if (isEditMode) {
        Arrangement.Top
    } else {
        Arrangement.Center
    }

    val loadPreset = {
        // Get the currently connected handpiece type from the MainViewModel
        val currentHandPieceType = mainViewModel.handPiece.value.type

        // Filter the main preset list based on the required conditions
        val filteredList = mainViewModel.presetList.value.filter { preset ->
            // This includes presets for the current handpiece OR common presets (type 0)
            preset.handPieceType == currentHandPieceType || preset.handPieceType == 0
        }

        // init
        presetViewModel.setIsEditMode(false)

        // Now set the presetViewModel's list with this newly filtered list
        presetViewModel.setPresetListSorted(filteredList)
        Timber.d("loadPreset function executed. Filtered list count: ${filteredList.size}")
    }


    LaunchedEffect(Unit) {
        //presetViewModel.clearPreset()
        loadPreset()

        focusManager.clearFocus(force = true) // Hide the keyboard
    }

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

    FullScreen {
        Column(
            modifier = Modifier
                .fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = contentAlignment
        ) {
            Spacer(modifier = Modifier.height(50.px.dp))

            // 전체 팝업 윈도
            Column(
                modifier = Modifier
                    .size(760.px.dp, 360.px.dp)
                    .clip(RoundedCornerShape(16.px.dp))
                    .background(Color.White)
                    .dropShadow(
                        shape = RoundedCornerShape(16.px.dp),
                        color = Color.Black.copy(alpha = 0.2f),
                        blur = 48.px.dp,
                        offsetX = 0.px.dp,
                        offsetY = 24.px.dp,
                        spread = 0.px.dp
                    )
                    .dropShadow(
                        shape = RoundedCornerShape(16.px.dp),
                        color = Color.Black.copy(alpha = 0.1f),
                        blur = 6.px.dp,
                        offsetX = 0.px.dp,
                        offsetY = 3.px.dp,
                        spread = 0.px.dp
                    )
                    .padding(10.px.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                // Title - (X 버튼 )
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(40.px.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ){
                    IconButton(
                        onClick = { presetViewModel.clearPreset(); onClick.invoke(false) },
                        modifier = Modifier.size(24.px.dp, 24.px.dp)
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_close),
                            contentDescription = null,
                            modifier = Modifier.size(24.px.dp),
                            contentScale = ContentScale.Crop
                        )
                    }
                }

                // Table 상단
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(32.px.dp)
                        .clip(RoundedCornerShape(topStart = 4.px.dp, topEnd = 4.px.dp))
                        .background(
                            brush = Brush.linearGradient(
                                colors = listOf(
                                    Color(255, 255, 255),
                                    Color(248, 245, 238),
                                )
                            )
                        )
                        .border(
                            width = 1.4.px.dp,
                            //color = Color.White,
                            brush = Brush.linearGradient(
                                colors = listOf(
                                    Color(183, 142, 9),
                                    Color(75, 63, 23)
                                ),
                                //start = Offset(0f, 0f), // Optional: Start at the top-left
                                //end = Offset(200f, 200f) // Optional: End at the bottom-right
                            ),
                            shape = RoundedCornerShape(topStart = 4.px.dp, topEnd = 4.px.dp),
                        )
                        .dropShadow(
                            shape = RoundedCornerShape(topStart = 4.px.dp, topEnd = 4.px.dp),
                            color = Color.Black.copy(alpha = 0.12f),
                            blur = 10.px.dp,
                            offsetX = 0.px.dp,
                            offsetY = 2.px.dp,
                            spread = 0.px.dp
                        ),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // Name
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .weight(2f)
                            .clip(RoundedCornerShape(topStart = 4.px.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(
                                        Color(47, 39, 14),
                                        Color(34, 33, 31),
                                    )
                                )
                            )
                            .innerShadow(
                                shape = RoundedCornerShape(topStart = 4.px.dp),
                                color = Color(255, 255, 255).copy(alpha = 0.15f),
                                blur = 4.px.dp,
                                offsetY = 4.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            ),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = "Name",
                            style = RobotoTypography.bodyMedium,
                            fontSize = 10.px.sp,
                            lineHeight = 20.px.sp,
                            letterSpacing = 0.25.px.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color.White,
                            textAlign = TextAlign.Center
                        )
                    }

                    VerticalDivider(
                        color = Color(228,228,231),
                        thickness = 1.px.dp,
                        modifier = Modifier
                            .fillMaxHeight()
                            .width(1.px.dp)
                    )

                    // HandPiece
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .weight(1f)
                            .clip(RoundedCornerShape(topStart = 4.px.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(
                                        Color(47, 39, 14),
                                        Color(34, 33, 31),
                                    )
                                )
                            )
                            .innerShadow(
                                shape = RoundedCornerShape(topStart = 4.px.dp),
                                color = Color(255, 255, 255).copy(alpha = 0.15f),
                                blur = 4.px.dp,
                                offsetY = 4.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            ),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = "HandPiece (mm)",
                            style = RobotoTypography.bodyMedium,
                            fontSize = 10.px.sp,
                            lineHeight = 10.px.sp,
                            letterSpacing = 0.25.px.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color.White,
                            textAlign = TextAlign.Center
                        )
                    }

                    VerticalDivider(
                        color = Color(228,228,231),
                        thickness = 1.px.dp,
                        modifier = Modifier
                            .fillMaxHeight()
                            .width(1.px.dp)
                    )

                    // PulseWidth
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .weight(1f)
                            .clip(RoundedCornerShape(topStart = 4.px.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(
                                        Color(47, 39, 14),
                                        Color(34, 33, 31),
                                    )
                                )
                            )
                            .innerShadow(
                                shape = RoundedCornerShape(topStart = 4.px.dp),
                                color = Color(255, 255, 255).copy(alpha = 0.15f),
                                blur = 4.px.dp,
                                offsetY = 4.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            ),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = "PulseWidth (ms)",
                            style = RobotoTypography.bodyMedium,
                            fontSize = 10.px.sp,
                            lineHeight = 10.px.sp,
                            letterSpacing = 0.25.px.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color.White,
                            textAlign = TextAlign.Center
                        )
                    }

                    VerticalDivider(
                        color = Color(228,228,231),
                        thickness = 1.px.dp,
                        modifier = Modifier
                            .fillMaxHeight()
                            .width(1.px.dp)
                    )

                    // Fluence
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .weight(1f)
                            .clip(RoundedCornerShape(topStart = 4.px.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(
                                        Color(47, 39, 14),
                                        Color(34, 33, 31),
                                    )
                                )
                            )
                            .innerShadow(
                                shape = RoundedCornerShape(topStart = 4.px.dp),
                                color = Color(255, 255, 255).copy(alpha = 0.15f),
                                blur = 4.px.dp,
                                offsetY = 4.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            ),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = "Fluence (J/cm²)",
                            style = RobotoTypography.bodyMedium,
                            fontSize = 10.px.sp,
                            lineHeight = 10.px.sp,
                            letterSpacing = 0.25.px.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color.White,
                            textAlign = TextAlign.Center
                        )
                    }

                    VerticalDivider(
                        color = Color(228,228,231),
                        thickness = 1.px.dp,
                        modifier = Modifier
                            .fillMaxHeight()
                            .width(1.px.dp)
                    )

                    // Repetition
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .weight(1f)
                            .clip(RoundedCornerShape(topStart = 4.px.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(
                                        Color(47, 39, 14),
                                        Color(34, 33, 31),
                                    )
                                )
                            )
                            .innerShadow(
                                shape = RoundedCornerShape(topStart = 4.px.dp),
                                color = Color(255, 255, 255).copy(alpha = 0.15f),
                                blur = 4.px.dp,
                                offsetY = 4.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            ),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = "Repetition (Hz)",
                            style = RobotoTypography.bodyMedium,
                            fontSize = 10.px.sp,
                            lineHeight = 10.px.sp,
                            letterSpacing = 0.25.px.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color.White,
                            textAlign = TextAlign.Center
                        )
                    }

                    VerticalDivider(
                        color = Color(228,228,231),
                        thickness = 1.px.dp,
                        modifier = Modifier
                            .fillMaxHeight()
                            .width(1.px.dp)
                    )

                    // Priority
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .weight(1f)
                            .clip(RoundedCornerShape(topStart = 4.px.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(
                                        Color(47, 39, 14),
                                        Color(34, 33, 31),
                                    )
                                )
                            )
                            .innerShadow(
                                shape = RoundedCornerShape(topStart = 4.px.dp),
                                color = Color(255, 255, 255).copy(alpha = 0.15f),
                                blur = 4.px.dp,
                                offsetY = 4.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            ),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = "Priority",
                            style = RobotoTypography.bodyMedium,
                            fontSize = 10.px.sp,
                            lineHeight = 20.px.sp,
                            letterSpacing = 0.25.px.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color.White,
                            textAlign = TextAlign.Center
                        )
                    }
                }

                // Table 하단
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.px.dp)  // 230
                        .clip(RoundedCornerShape(bottomStart = 4.px.dp, bottomEnd = 4.px.dp))
                        .background(
                            brush = Brush.linearGradient(
                                colors = listOf(
                                    Color(255, 255, 255),
                                    Color(248, 245, 238),
                                )
                            )
                        )
                        .border(
                            width = 1.4.px.dp,
                            //color = Color.White,
                            brush = Brush.linearGradient(
                                colors = listOf(
                                    Color(183, 142, 9),
                                    Color(75, 63, 23)
                                ),
                                //start = Offset(0f, 0f), // Optional: Start at the top-left
                                //end = Offset(200f, 200f) // Optional: End at the bottom-right
                            ),
                            shape = RoundedCornerShape(bottomStart = 4.px.dp, bottomEnd = 4.px.dp),
                        )
                        .dropShadow(
                            shape = RoundedCornerShape(bottomStart = 4.px.dp, bottomEnd = 4.px.dp),
                            color = Color.Black.copy(alpha = 0.12f),
                            blur = 10.px.dp,
                            offsetX = 0.px.dp,
                            offsetY = 2.px.dp,
                            spread = 0.px.dp
                        ),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // Preset Lists.
                    PresetLoadList(
                        modifier = Modifier.fillMaxSize(),
                        presetViewModel = presetViewModel,
                    )
                }

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

                // Buttons(Preset1..5, Delete, Edit, Save)
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(88.px.dp),  // 88
                    //.padding(start = 10.px.dp, end = 10.px.dp),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    if (isEditMode) {
                        ////////////////////////////////////////////////////
                        // Edit Mode

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

                        // Preset Delete (Delete confirm popup)
                        Box(
                            modifier = Modifier
                                .noRippleClickable(onClick = {
                                    Timber.d("onClick - Preset Delete")
                                    showDeleteConfirmDialog = true
                                })
                                .size(40.px.dp)
                                .background(Color.Transparent)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.ic_delete_btn),
                                contentDescription = "Preset Load",
                                modifier = Modifier
                                    .size(40.px.dp)
                                    .align(Alignment.BottomCenter),
                                contentScale = ContentScale.Crop
                            )
                        }

                        Spacer(Modifier.weight(1f))

                        // Preset Cancel (Reload selected item from mainViewModel)
                        Box(
                            modifier = Modifier
                                .noRippleClickable(onClick = {
                                    Timber.d("onClick - Preset Cancel")

                                    // Find preset Item with selectedIndex from PresetViewModel
                                    val selectedPreset =
                                        presetViewModel.getPreset(selectedPresetIndex)
                                    if (selectedPreset == null) {
                                        Timber.e("refreshPresetById: Could not find preset with selectedPresetIndex $selectedPresetIndex in PresetViewModel.")
                                        Toast.makeText(
                                            context,
                                            "Could not find preset with selectedPresetIndex $selectedPresetIndex in PresetViewModel.",
                                            Toast.LENGTH_LONG
                                        ).show()
                                        return@noRippleClickable
                                    }

                                    // Find the preset from MainViewModel's list.
                                    val masterPreset =
                                        mainViewModel.presetList.value.find { it.id == selectedPreset.id }
                                    if (masterPreset == null) {
                                        Timber.w("refreshPresetById: Could not find preset with ID ${selectedPreset.id} in MainViewModel.")
                                        Toast.makeText(
                                            context,
                                            "refreshPresetById: Could not find preset with ID ${selectedPreset.id} in MainViewModel.",
                                            Toast.LENGTH_LONG
                                        ).show()
                                        return@noRippleClickable
                                    }

                                    // Set the masterPreset to PresetViewModel
                                    presetViewModel.setPreset(masterPreset)

                                    /*
                                    Toast.makeText(
                                        context,
                                        "Preset list update completed.",
                                        Toast.LENGTH_LONG
                                    ).show()
                                    */
                                })
                                .size(40.px.dp)
                                .background(Color.Transparent)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.ic_cancel_btn),
                                contentDescription = "Preset Cancel",
                                modifier = Modifier
                                    .size(40.px.dp)
                                    .align(Alignment.BottomCenter),
                                contentScale = ContentScale.Crop
                            )
                        }

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

                        // Preset Save Confirm
                        Box(
                            modifier = Modifier
                                .noRippleClickable(onClick = {
                                    // save presetList to mainViewModel
                                    Timber.d("onClick - Confirm Save")

                                    // Check empty names and conflict priority exist in the preset viewmodel's presetList
                                    val listToValidate = presetViewModel.presetList.value

                                    // Check for any presets with an empty name
                                    val hasEmptyName =
                                        listToValidate.any { it.name.trim().isEmpty() }
                                    if (hasEmptyName) {
                                        Toast.makeText(
                                            context,
                                            "One or more presets have an empty name. Please correct it.",
                                            Toast.LENGTH_LONG
                                        ).show()
                                        return@noRippleClickable // Stop the process
                                    }

                                    // Check 2: Are there any duplicate names among the non-empty ones?
                                    val nameConflicts = listToValidate
                                        .filter {
                                            it.name.trim().isNotEmpty()
                                        }     // Only consider non-empty names
                                        .groupBy { it.name.trim() }                 // Group by name
                                        .any { it.value.size > 1 }                  // See if any group has duplicates

                                    if (nameConflicts) {
                                        Toast.makeText(
                                            context,
                                            "There are duplicate preset names. Please ensure each name is unique.",
                                            Toast.LENGTH_LONG
                                        ).show()
                                        return@noRippleClickable // Stop the process
                                    }

                                    // Check for duplicate priorities (ignoring priority 0)
                                    val priorityConflicts = listToValidate
                                        .filter { it.priority > 0 } // Only consider prioritized items
                                        .groupBy { it.priority }   // Group them by priority
                                        .any { it.value.size > 1 } // Check if any group is larger than 1

                                    if (priorityConflicts) {
                                        Toast.makeText(
                                            context,
                                            "There are duplicate priorities. Please ensure each priority is unique.",
                                            Toast.LENGTH_LONG
                                        ).show()
                                        return@noRippleClickable // Stop the process
                                    }

                                    Timber.d("Validation successful. Saving list to MainViewModel.")

                                    // Save presetList to mainViewModel
                                    mainViewModel.setPresetList(presetViewModel.presetList.value)

                                    scope.launch {
                                        mainViewModel.savePresetListToPreference()
                                    }

                                    /*
                                    Toast.makeText(
                                        context,
                                        "Preset edit done.",
                                        Toast.LENGTH_LONG
                                    ).show()
                                    */

                                    // remove preset
                                    presetViewModel.clearPreset()

                                    // Toggle edit mode
                                    //presetViewModel.setIsEditMode(false)

                                    loadPreset()
                                })
                                .size(40.px.dp)
                                .background(Color.Transparent)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.ic_save_btn),
                                contentDescription = "Preset Load",
                                modifier = Modifier
                                    .size(40.px.dp)
                                    .align(Alignment.BottomCenter),
                                contentScale = ContentScale.Crop
                            )
                        }

                        Spacer(modifier = Modifier.width(10.px.dp))
                    } else {
                        Spacer(Modifier.weight(1f))

                        ////////////////////////////////////////////////////
                        // Select Mode - hide Keyboard
                        focusManager.clearFocus(force = true) // Hide the keyboard

                        // [Edit Btn]
                        Box(
                            modifier = Modifier
                                .noRippleClickable(onClick = {
                                    Timber.d("onClick - Preset Edit")
                                    presetViewModel.setIsEditMode(true) // //presetViewModel.toggleIsEditMode()
                                })
                                .size(40.px.dp)
                                .background(Color.Transparent)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.ic_edit_btn),
                                contentDescription = "Preset Load",
                                modifier = Modifier
                                    .size(40.px.dp)
                                    .align(Alignment.BottomCenter),
                                contentScale = ContentScale.Crop
                            )
                        }

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

                        // [Load Btn]
                        Box(
                            modifier = Modifier
                                .noRippleClickable(onClick = {
                                    Timber.d("onClick - Preset Load")

                                    val selectedPreset =
                                        presetViewModel.getPreset(selectedPresetIndex)
                                    val priority =
                                        selectedPreset?.priority ?: 0

                                    Timber.d("onClick - Preset Load ($priority)")

//                                    if (priority > 0) {   // TODO : 검증 필요
                                        mainViewModel.setSelectedPresetIndex( priority )
                                        mainViewModel.applyPreset(priority)
                                        presetViewModel.clearPreset()
                                        onClick.invoke(false)
//                                    } else {
//                                        Timber.d("SKIP - Preset Load ($priority)")
//                                    }
                                })
                                .size(40.px.dp)
                                .background(Color.Transparent)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.ic_load_btn),
                                contentDescription = "Preset Load",
                                modifier = Modifier
                                    .size(40.px.dp)
                                    .align(Alignment.BottomCenter),
                                contentScale = ContentScale.Crop
                            )
                        }

                        Spacer(modifier = Modifier.width(10.px.dp))
                    }
                }

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

        ///////////////////////////////////////////////////////////////////////////////////////////
        // Popup
        if (showDeleteConfirmDialog) {
            DeleteConfirmDialog(
                title = stringResource(R.string.delete_confirm_title),
                onClick = { ok ->
                    if (ok) {
                        Timber.d("onClick - Delete Confirm OK")

                        // remove from View
                        presetViewModel.deletePreset(selectedPresetIndex)

                        // reset index
                        if (selectedPresetIndex > 0) {
                            presetViewModel.setSelectedPresetIndex(selectedPresetIndex -1)
                        } else {
                            presetViewModel.setSelectedPresetIndex(0)
                        }
                    } else {
                        Timber.d("onClick - Delete Confirm Cancel")
                    }
                    showDeleteConfirmDialog = false
                }
            )

        }
    }
}

@Composable
fun PresetLoadList(
    modifier: Modifier = Modifier,
    presetViewModel: PresetViewModel = hiltViewModel<PresetViewModel>(),
) {
    val selectedPresetIndex by presetViewModel.selectedPresetIndex.collectAsState()
    val isEditMode by presetViewModel.isEditMode.collectAsState()
    val listData by presetViewModel.presetList.collectAsState()
    val state = rememberLazyListState(selectedPresetIndex)

    LazyColumn(
        modifier = modifier.simpleVerticalScrollbar(state),
        state = state
    ) {
        itemsIndexed(
            items = listData,
            key = { index, item -> item.id }
        ) { index, presetItem ->
            //val index = presets.size -1 - rIndex
            Timber.d("index --> $index, priority: ${presetItem.priority}")
            PresetLoadRow(
                preset = presetItem,
                index = index,
                selectedPresetIndex = selectedPresetIndex,
                isEditMode = isEditMode,
                onItemClickListener = { idx ->
                    Timber.d("Preset Item Clicked(${idx}, index: ${index})")
                    if (!isEditMode) {
                        presetViewModel.setSelectedPresetIndex(idx)
                    }
                },
                onNameChange = { itemIndex, newName ->
                    Timber.d("Preset onNameChange (${itemIndex}, index: ${index}, newName: ${newName})")
                    presetViewModel.updatePresetName(itemIndex, newName)
                },
                onHandPieceTypeChange = { itemIndex, handPieceType, /* pulseWidth, fluence, repetition,*/ isUp ->
                    Timber.d("Preset onHandPieceTypeChange (${itemIndex}, index: ${index}, isUp: ${isUp})")
                    presetViewModel.updateHandPieceType(itemIndex, handPieceType, /* pulseWidth, fluence, repetition,*/ isUp)
                },
                onPulseWidthChange = { itemIndex, handPieceType, pulseWidth, /* fluence, repetition,*/ isUp ->
                    Timber.d("Preset onPulseWidthChange (${itemIndex}, index: ${index}, pulseWidth: ${pulseWidth} isUp: ${isUp})")
                    presetViewModel.updatePulseWidth(itemIndex, handPieceType, pulseWidth, /* fluence, repetition,*/ isUp)
                },
                onFluenceChange = { itemIndex, handPieceType, pulseWidth, /* fluence, */ repetition, isUp ->
                    Timber.d("Preset onFluenceChange (${itemIndex}, index: ${index}, pulseWidth: ${pulseWidth}, repetition: ${repetition}, isUp: ${isUp})")
                    presetViewModel.updateFluence(itemIndex, handPieceType, pulseWidth, /* fluence, */ repetition, isUp)
                },
                onRepetitionChange = { itemIndex, handPieceType, pulseWidth, fluence, repetition, isUp ->
                    Timber.d("Preset onRepetitionChange (${itemIndex}, index: ${index}, pulseWidth: ${pulseWidth}, fluence: ${fluence}, repetition: ${repetition}, isUp: ${isUp})")
                    presetViewModel.updateRepetition(itemIndex, handPieceType, pulseWidth, fluence, repetition, isUp)
                },
                onPriorityChange = { itemIndex, priority, isUp ->
                    Timber.d("Preset onPriorityChange (${itemIndex}, index: ${index}, priority: ${priority}, isUp: ${isUp})")
                    presetViewModel.updatePriority(itemIndex, priority, isUp)
                },
            )

            // divider
            HorizontalDivider(
                color = Color(228, 228, 231),
                thickness = 1.px.dp,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(1.px.dp)
            )
        }
    }
}

@Composable
fun PresetLoadRow(
    preset: Preset = Preset(),
    index: Int = 0,
    selectedPresetIndex: Int = 0,
    isEditMode: Boolean = false,
    onItemClickListener: (Int) -> Unit,
    onNameChange: (Int, String) -> Unit,
    onHandPieceTypeChange: (Int, Int, UpDownState) -> Unit,
    onPulseWidthChange: (Int, Int, Float, UpDownState) -> Unit,
    onFluenceChange: (Int, Int, Float, Float, UpDownState) -> Unit,
    onRepetitionChange: (Int, Int, Float, Float, Float, UpDownState) -> Unit,
    onPriorityChange: (Int, Int, UpDownState) -> Unit,
) {
    val focusManager = LocalFocusManager.current
    val focusRequester = remember { FocusRequester() }
    var textFieldValue by remember(preset.name) {
        mutableStateOf(
            TextFieldValue(
                text = preset.name,
                selection = TextRange(preset.name.length) // Default selection to the end
            )
        )
    }

    Row(
        modifier = Modifier
            .noRippleClickable { onItemClickListener(index) }
            /*
            .combinedClickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null, // This removes the ripple effect
                onClick = {
                    Timber.d("Short click on row $index")
                },
                onLongClick = {
                    onItemClickListener(index)
                    Timber.d("Long click on row $index")
                }
            )
            */
            .fillMaxWidth()
            .height(37.px.dp)
            //.border(width = 2.px.dp, color = Color(200,56,4)),
            .background(
                color = if (selectedPresetIndex == index) Color(254, 245, 216) else Color.White
            ),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // Name - Value
        Column(
            modifier = Modifier
                .fillMaxSize()
                .weight(2f)
                .background(Color.Transparent),
            //.border(width = 1.px.dp, color = Color(228,228,231)),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            if (isEditMode && index == selectedPresetIndex) {
                // EditBox
                BasicTextField(
                    value = textFieldValue,
                    onValueChange = { newTextFieldValue ->
                        textFieldValue = newTextFieldValue
                        Timber.d("newText for index $index, ${newTextFieldValue.text}")
                        onNameChange(index, newTextFieldValue.text) },
                    modifier = Modifier
                        .fillMaxWidth() // Fill the width of the parent Row
                        .weight(1f)     // If other elements were in the Row, this helps fill space
                        .focusRequester(focusRequester),
                    textStyle = robotoTextStyle.copy( // Use your existing text style
                        fontSize = 14.px.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Center // This centers the input text
                    ),
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Password, // KeyboardType.Text,
                        imeAction = ImeAction.Done,
                        //autoCorrect = false
                    ),
                    keyboardActions = KeyboardActions(onDone = {
                        focusManager.clearFocus(force = true)
                    }),
                    decorationBox = { innerTextField ->
                        // This Box helps in positioning the placeholder and the input area
                        Box(
                            modifier = Modifier.fillMaxWidth(), // Ensure the Box takes full width for textAlign
                            contentAlignment = Alignment.Center // Center placeholder and input text
                        ) {
                            innerTextField() // This is where the actual editable text appears
                        }
                    }
                )
                LaunchedEffect(Unit) {
                    Timber.d("focusRequester.requestFocus()")
                    focusRequester.requestFocus()
                }
            } else {
                Text(
                    text = preset.name, // preset.name,
                    style = RobotoTypography.bodyMedium,
                    fontSize = 14.px.sp,
                    letterSpacing = 0.25.px.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black,
                    textAlign = TextAlign.Center
                )
            }

        }

        VerticalDivider(
            color = Color(228,228,231),
            thickness = 1.px.dp,
            modifier = Modifier
                .fillMaxHeight()
                .width(1.px.dp)
        )

        // HandPiece - Value
        Column(
            modifier = Modifier
                .fillMaxSize()
                .weight(1f)
                .background(Color.Transparent),
            //.border(width = 1.px.dp, color = Color(228,228,231)),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Row (
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = handPieceTypes.get(preset.handPieceType),
                    style = RobotoTypography.bodyMedium,
                    fontSize = 14.px.sp,
                    letterSpacing = 0.25.px.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black,
                    textAlign = TextAlign.Center
                )
            }
        }

        VerticalDivider(
            color = Color(228,228,231),
            thickness = 1.px.dp,
            modifier = Modifier
                .fillMaxHeight()
                .width(1.px.dp)
        )

        // PulseWidth - Value
        Column(
            modifier = Modifier
                .fillMaxSize()
                .weight(1f)
                .background(Color.Transparent),
            //.border(width = 1.px.dp, color = Color(228,228,231)),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Row (
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (isEditMode && index == selectedPresetIndex) {
                    Spacer(Modifier.weight(1f))
                    GradientImageButton(
                        id = R.drawable.ic_arrow_up,
                        onClick = {
                            // PulseWidth up
                            Timber.d("PulseWidth up")
                            onPulseWidthChange(index, preset.handPieceType, preset.pulseWidth, UpDownState.Up)
                        }
                    )
                    Spacer(Modifier.weight(1f))
                }

                Text(
                    text = preset.pulseWidth.toString(),
                    style = RobotoTypography.bodyMedium,
                    fontSize = 14.px.sp,
                    letterSpacing = 0.25.px.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black,
                    textAlign = TextAlign.Center
                )

                if (isEditMode && index == selectedPresetIndex) {
                    Spacer(Modifier.weight(1f))
                    GradientImageButton(
                        id = R.drawable.ic_arrow_down,
                        onClick = {
                            // PulseWidth down
                            Timber.d("PulseWidth down")
                            onPulseWidthChange(index, preset.handPieceType, preset.pulseWidth, UpDownState.Down)
                        }
                    )
                    Spacer(Modifier.weight(1f))
                }
            }
        }

        VerticalDivider(
            color = Color(228,228,231),
            thickness = 1.px.dp,
            modifier = Modifier
                .fillMaxHeight()
                .width(1.px.dp)
        )

        // Fluence - Value
        Column(
            modifier = Modifier
                .fillMaxSize()
                .weight(1f)
                .background(Color.Transparent),
            //.border(width = 1.px.dp, color = Color(228,228,231)),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Row (
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (isEditMode && index == selectedPresetIndex) {
                    Spacer(Modifier.weight(1f))
                    GradientImageButton(
                        id = R.drawable.ic_arrow_up,
                        onClick = {
                            // Fluence up
                            Timber.d("Fluence up")
                            onFluenceChange(index, preset.handPieceType, preset.pulseWidth, preset.fluence, UpDownState.Up)
                        }
                    )
                    Spacer(Modifier.weight(1f))
                }

                Text(
                    text = preset.fluence.toString(),
                    style = RobotoTypography.bodyMedium,
                    fontSize = 14.px.sp,
                    letterSpacing = 0.25.px.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black,
                    textAlign = TextAlign.Center
                )

                if (isEditMode && index == selectedPresetIndex) {
                    Spacer(Modifier.weight(1f))
                    GradientImageButton(
                        id = R.drawable.ic_arrow_down,
                        onClick = {
                            // Fluence down
                            Timber.d("Fluence down")
                            onFluenceChange(index, preset.handPieceType, preset.pulseWidth, preset.fluence, UpDownState.Down)
                        }
                    )
                    Spacer(Modifier.weight(1f))
                }
            }
        }

        VerticalDivider(
            color = Color(228,228,231),
            thickness = 1.px.dp,
            modifier = Modifier
                .fillMaxHeight()
                .width(1.px.dp)
        )

        // repetition - Value
        Column(
            modifier = Modifier
                .fillMaxSize()
                .weight(1f)
                .background(Color.Transparent),
            //.border(width = 1.px.dp, color = Color(228,228,231)),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Row (
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (isEditMode && index == selectedPresetIndex) {
                    Spacer(Modifier.weight(1f))
                    GradientImageButton(
                        id = R.drawable.ic_arrow_up,
                        onClick = {
                            // repetition up
                            Timber.d("repetition up")
                            onRepetitionChange(index, preset.handPieceType, preset.pulseWidth, preset.fluence, preset.repetition, UpDownState.Up)
                        }
                    )
                    Spacer(Modifier.weight(1f))
                }

                Text(
                    text = preset.repetition.toString(),
                    style = RobotoTypography.bodyMedium,
                    fontSize = 14.px.sp,
                    letterSpacing = 0.25.px.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black,
                    textAlign = TextAlign.Center
                )

                if (isEditMode && index == selectedPresetIndex) {
                    Spacer(Modifier.weight(1f))
                    GradientImageButton(
                        id = R.drawable.ic_arrow_down,
                        onClick = {
                            // repetition down
                            Timber.d("repetition down")
                            onRepetitionChange(index, preset.handPieceType, preset.pulseWidth, preset.fluence, preset.repetition, UpDownState.Down)
                        }
                    )
                    Spacer(Modifier.weight(1f))
                }
            }
        }

        VerticalDivider(
            color = Color(228,228,231),
            thickness = 1.px.dp,
            modifier = Modifier
                .fillMaxHeight()
                .width(1.px.dp)
        )

        // priority - Value
        Column(
            modifier = Modifier
                .fillMaxSize()
                .weight(1f)
                .background(Color.Transparent),
            //.border(width = 1.px.dp, color = Color(228,228,231)),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {

            Row (
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (isEditMode && index == selectedPresetIndex) {
                    Spacer(Modifier.weight(1f))
                    GradientImageButton(
                        id = R.drawable.ic_arrow_up,
                        onClick = {
                            // priority up
                            Timber.d("priority up")
                            onPriorityChange(index, preset.priority, UpDownState.Up)
                        }
                    )
                    Spacer(Modifier.weight(1f))
                }


                Text(
                    text = if (preset.priority == 0) "NONE" else preset.priority.toString(),
                    style = RobotoTypography.bodyMedium,
                    fontSize = 14.px.sp,
                    letterSpacing = 0.25.px.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black,
                    textAlign = TextAlign.Center
                )

                if (isEditMode && index == selectedPresetIndex) {
                    Spacer(Modifier.weight(1f))
                    GradientImageButton(
                        id = R.drawable.ic_arrow_down,
                        onClick = {
                            // priority down
                            Timber.d("priority down")
                            onPriorityChange(index, preset.priority, UpDownState.Down)
                        }
                    )
                    Spacer(Modifier.weight(1f))
                }
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Previews
@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 PreviewPresetLoadPopup(
    mainViewModel:MainViewModel = MainViewModel(
        preferenceRepository = PreferenceRepository(LocalContext.current),
        serialPortRepository = SerialPortRepository.createWithFakeRepository(),
        databaseRepository = DatabaseRepository(RamanDatabaseService(RamanDatabase.getInstance(LocalContext.current))),
        dispatcherProvider = DefaultDispatcherProvider(),
        applicationContext = LocalContext.current
    )
) {
    Box {
        PresetLoadPopup(
            mainViewModel = mainViewModel,
        )
    }
}

/*
@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 PreviewPresetLoadList(
    presetViewModel:PresetViewModel = PresetViewModel()
) {
    Box {
        PresetLoadList(
            presetViewModel = presetViewModel,
        )
    }
}

@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 PreviewPresetLoadRow(
) {
    Box {
        PresetLoadRow(
            preset = Preset(
                name = "Name"
            ),
            index = 0,
            selectedPresetIndex = 0,
            isEditMode = false,
            onItemClickListener = { },
            onNameChange = { _, _ ->},
            onHandPieceTypeChange = { _, _, _ ->},
            onPulseWidthChange = { _, _, _, _ ->},
            onFluenceChange = { _, _, _, _, _ ->},
            onRepetitionChange = { _, _, _, _, _, _ ->},
            onPriorityChange = { _, _, _ ->},
        )
    }
}
*/
