package com.laseroptek.raman.ui.screens.engineer.energy

import android.content.res.Configuration
import android.widget.Toast
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.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.RoundedCornerShape
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.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.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.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
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 com.laseroptek.raman.R
import com.laseroptek.raman.const.DEFAULT_REFER1_VALUE
import com.laseroptek.raman.const.MAX_REFER1_VALUE
import com.laseroptek.raman.ui.common.fullscreen.FullScreen
import com.laseroptek.raman.ui.theme.RobotoTypography
import com.laseroptek.raman.utils.ext.dropShadow
import com.laseroptek.raman.utils.ext.noRippleClickable
import com.laseroptek.raman.utils.ext.px
import timber.log.Timber

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Refer1Popup(
    title: String = stringResource(R.string.energy_detect_refer1_title),
    hpType: Int = 1,        // handpiece type no (1..n-1)
    measured: Int = DEFAULT_REFER1_VALUE,      // energy measured value (READ)
    measuredWrite: Int = DEFAULT_REFER1_VALUE, // energy measured value (WRITE)(INTERNAL)
    maxValue: Int = MAX_REFER1_VALUE,
    onClickRead: () -> Unit = {},
    onClickCancel: () -> Unit = {},
    onClickSet: (Int) -> Unit = {},   // energy measured value (WRITE)(EXTENRAL)
) {
    val context = LocalContext.current
    var textFieldValue by remember {
        mutableStateOf(
            // Initialize TextFieldValue with the text and set the cursor to the end.
            TextFieldValue(
                text = measuredWrite.toString(),
                selection = TextRange(measuredWrite.toString().length) // This places the cursor at the end
            )
        )
    }
    val focusManager = LocalFocusManager.current
    val focusRequester = remember { FocusRequester() }
    val performSetClick = {
        val text = textFieldValue.text
        if (text.isEmpty()) {
            Toast.makeText(context, "Input Number", Toast.LENGTH_SHORT).show()
        } else {
            focusManager.clearFocus()
            // Use toIntOrNull for safety, though validation should prevent crashes
            val newValue = text.toIntOrNull() ?: 0
            Timber.d("OK action performed with value: ${newValue}")
            onClickSet(newValue)
        }
    }

    // TabView
    var tabIndex by remember { mutableStateOf(0) }
    val selectedBackgroundBrush = Brush.verticalGradient(
        colors = listOf(
            Color(47, 51, 57),
            Color(83, 88, 97),
        )
    )
    val selectedBorderBrush = Brush.verticalGradient(
        colors = listOf(
            Color(92, 99, 107),
            Color(34, 34, 1),
        )
    )

    LaunchedEffect(Unit) {
        Timber.d("focusRequester.requestFocus()")
        focusRequester.requestFocus()
    }

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

    FullScreen {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 50.px.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            Column(
                modifier = Modifier
                    .size(420.px.dp, 360.px.dp)
                    .clip(RoundedCornerShape(28.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(start = 24.px.dp, end = 24.px.dp, top = 10.px.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Top
            ) {
                // Title
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.px.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically
                ){
                    Text(
                        text = title,
                        style = RobotoTypography.headlineLarge,
                        fontWeight = FontWeight.ExtraLight,
                        fontSize = 24.px.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Center,
                    )
                }

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

                // HandPiece View
                Row(modifier = Modifier
                    .fillMaxWidth()
                    .height(52.px.dp)
                ) {
                    HandPieceView(hpType = hpType)
                }

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

                // Tab Selection
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(52.px.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Start,
                ) {
                    Row(
                        modifier = Modifier
                            .size(296.px.dp, 38.px.dp)
                            .border(
                                width = 0.5.px.dp,
                                color = Color(209,209,209),
                                shape = RoundedCornerShape(8.px.dp)
                            ),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // Internal
                        Column(
                            modifier = Modifier
                                .noRippleClickable(onClick = { tabIndex = 0 })
                                .size(145.px.dp, 32.px.dp)
                                .background(
                                    brush = if (tabIndex == 0) selectedBackgroundBrush else SolidColor(Color.Transparent),
                                    shape = RoundedCornerShape(8.px.dp)
                                )
                                .border(
                                    width = 0.5.px.dp,
                                    brush = if (tabIndex == 0) selectedBorderBrush else SolidColor(
                                        Color.Transparent
                                    ),
                                    shape = RoundedCornerShape(8.px.dp)
                                )
                                .dropShadow(
                                    shape = RoundedCornerShape(8.px.dp),
                                    color = if (tabIndex == 0) Color(243, 205, 81).copy(alpha = 0.2f) else Color.Transparent,
                                    blur = 3.5.px.dp,
                                    offsetY = 0.px.dp,
                                    offsetX = 0.px.dp,
                                    spread = 0.px.dp
                                )
                                .dropShadow(
                                    shape = RoundedCornerShape(8.px.dp),
                                    color = if (tabIndex == 0) Color(0, 0, 0).copy(alpha = 0.1f) else Color.Transparent,
                                    blur = 1.75.px.dp,
                                    offsetY = 1.75.px.dp,
                                    offsetX = 0.px.dp,
                                    spread = 0.px.dp
                                ),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Text(
                                text = "Internal",
                                style = RobotoTypography.bodySmall.copy(
                                    fontSize = 16.px.sp,
                                    fontWeight = FontWeight.ExtraLight
                                ),
                                textAlign = TextAlign.Center,
                                color = if (tabIndex == 0) Color.White else Color.Black,
                            )
                        }

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

                        // External
                        Column(
                            modifier = Modifier
                                .noRippleClickable(onClick = { tabIndex = 1 })
                                .size(145.px.dp, 32.px.dp)
                                .background(
                                    brush = if (tabIndex == 1) selectedBackgroundBrush else SolidColor(Color.Transparent),
                                    shape = RoundedCornerShape(8.px.dp)
                                )
                                .border(
                                    width = 0.5.px.dp,
                                    brush = if (tabIndex == 1) selectedBorderBrush else SolidColor(Color.Transparent),
                                    shape = RoundedCornerShape(8.px.dp)
                                )
                                .dropShadow(
                                    shape = RoundedCornerShape(8.px.dp),
                                    color = if (tabIndex == 1) Color(243, 205, 81).copy(alpha = 0.2f) else Color.Transparent,
                                    blur = 3.5.px.dp,
                                    offsetY = 0.px.dp,
                                    offsetX = 0.px.dp,
                                    spread = 0.px.dp
                                )
                                .dropShadow(
                                    shape = RoundedCornerShape(8.px.dp),
                                    color = if (tabIndex == 1) Color(0, 0, 0).copy(alpha = 0.1f) else Color.Transparent,
                                    blur = 1.75.px.dp,
                                    offsetY = 1.75.px.dp,
                                    offsetX = 0.px.dp,
                                    spread = 0.px.dp
                                ),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Text(
                                text = "External",
                                style = RobotoTypography.bodySmall.copy(
                                    fontSize = 16.px.sp,
                                    fontWeight = FontWeight.ExtraLight
                                ),
                                textAlign = TextAlign.Center,
                                color = if (tabIndex == 1) Color.White else Color.Black,
                            )
                        }
                    }
                }

                // Internal
                if (tabIndex == 0) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height( 100.px.dp),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxSize()
                                .weight(1f),
                            horizontalAlignment = Alignment.Start,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Text(
                                text = "Read",
                                style = RobotoTypography.bodySmall,
                                fontWeight = FontWeight.Thin,
                                fontSize = 14.px.sp,
                                color = Color.Black
                            )

                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(56.px.dp)
                                    .background(Color(245,245,245))
                                    .border(width = 1.px.dp, Color.LightGray,),
                                horizontalArrangement = Arrangement.Start,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = "  %d".format(measured),
                                    style = RobotoTypography.bodySmall,
                                    fontWeight = FontWeight.Thin,
                                    fontSize = 16.px.sp,
                                    color = Color.Black.copy(alpha = 0.5f)
                                )
                            }

                            HorizontalDivider(thickness = 1.px.dp, color = Color(0,0,0).copy(alpha = 0.38f))
                        }

                        // Dividier
                        //Spacer(Modifier.width(10.px.dp))
                        VerticalDivider(
                            color = Color(209, 209, 209),
                            thickness = 1.px.dp,
                            modifier = Modifier
                                .padding(top = 20.px.dp, bottom = 10.px.dp, start = 10.px.dp, end = 10.px.dp)
                        )
                        //Spacer(Modifier.width(10.px.dp))

                        Column(
                            modifier = Modifier
                                .fillMaxSize()
                                .weight(1f),
                            horizontalAlignment = Alignment.Start,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Text(
                                text = "Write",
                                style = RobotoTypography.bodySmall,
                                fontWeight = FontWeight.Thin,
                                fontSize = 14.px.sp,
                                color = Color.Black
                            )

                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(56.px.dp)
                                    .background(Color(245,245,245))
                                    .border(width = 1.px.dp, Color.LightGray,),
                                horizontalArrangement = Arrangement.Start,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                OutlinedTextField(
                                    value = textFieldValue,
                                    onValueChange = { newTextFieldValue ->
                                        val newText = newTextFieldValue.text
                                        if (newText.isEmpty()) {
                                            textFieldValue = newTextFieldValue
                                        } else if (newText.all { it.isDigit() }) {
                                            // Safely parse to Long to avoid NumberFormatException on large numbers
                                            val number = newText.toLongOrNull()
                                            if (number != null && number <= maxValue) {
                                                textFieldValue = newTextFieldValue
                                            } else {
                                                // The number is too large or invalid, show a toast
                                                Toast.makeText(
                                                    context,
                                                    "Input Number exceeded max value of $maxValue",
                                                    Toast.LENGTH_SHORT
                                                ).show()
                                            }
                                        }
                                    },
                                    //label = { Text("Count") },
                                    keyboardOptions = KeyboardOptions(
                                        keyboardType = KeyboardType.NumberPassword, // KeyboardType.Number, //KeyboardType.Text
                                        imeAction = ImeAction.Done,
                                        //autoCorrect = false
                                    ),
                                    singleLine = true,
                                    keyboardActions = KeyboardActions(onDone = {
                                        performSetClick()
                                    }),
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .focusRequester(focusRequester)
                                        .background(Color.Transparent)
                                )

                                LaunchedEffect(Unit) {
                                    Timber.d("focusRequester.requestFocus()")
                                    focusRequester.requestFocus()
                                }

                            }

                            HorizontalDivider(thickness = 1.px.dp, color = Color(0,0,0).copy(alpha = 0.38f))
                        }
                    }
                } else {
                    // External
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height( 100.px.dp),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxSize()
                                .weight(1f),
                            horizontalAlignment = Alignment.Start,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Text(
                                text = "Read",
                                style = RobotoTypography.bodySmall,
                                fontWeight = FontWeight.Thin,
                                fontSize = 14.px.sp,
                                color = Color.Black
                            )

                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(56.px.dp)
                                    .background(Color(245,245,245))
                                    .border(width = 1.px.dp, Color.LightGray,),
                                horizontalArrangement = Arrangement.Start,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = "  %d".format(measured),
                                    style = RobotoTypography.bodySmall,
                                    fontWeight = FontWeight.Thin,
                                    fontSize = 16.px.sp,
                                    color = Color.Black.copy(alpha = 0.5f)
                                )
                            }

                            HorizontalDivider(thickness = 1.px.dp, color = Color(0,0,0).copy(alpha = 0.38f))
                        }

                        VerticalDivider(
                            color = Color(209, 209, 209),
                            thickness = 1.px.dp,
                            modifier = Modifier
                                .padding(top = 20.px.dp, bottom = 10.px.dp, start = 10.px.dp, end = 10.px.dp)
                        )

                        Column(
                            modifier = Modifier
                                .fillMaxSize()
                                .weight(1f),
                            horizontalAlignment = Alignment.Start,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Text(
                                text = "Write",
                                style = RobotoTypography.bodySmall,
                                fontWeight = FontWeight.Thin,
                                fontSize = 14.px.sp,
                                color = Color.Black
                            )

                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(56.px.dp)
                                    .background(Color(245,245,245))
                                    .border(width = 1.px.dp, Color.LightGray,),
                                horizontalArrangement = Arrangement.Start,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                OutlinedTextField(
                                    value = textFieldValue,
                                    onValueChange = { newTextFieldValue ->
                                        val newText = newTextFieldValue.text
                                        if (newText.isEmpty() ||
                                            (newText.length < 10 && newText.all { char -> char.isDigit() })
                                        ) {
                                            // Update the state with the new TextFieldValue object
                                            textFieldValue = newTextFieldValue
                                        } else {
                                            Toast.makeText(
                                                context,
                                                "Input Number exceeded max value ${maxValue}",
                                                Toast.LENGTH_SHORT
                                            ).show()
                                        }
                                    },
                                    //label = { Text("Count") },
                                    keyboardOptions = KeyboardOptions(
                                        keyboardType = KeyboardType.NumberPassword, // KeyboardType.Number, //KeyboardType.Text
                                        imeAction = ImeAction.Done,
                                        //autoCorrect = false
                                    ),
                                    singleLine = true,
                                    keyboardActions = KeyboardActions(onDone = {
                                        performSetClick()
                                    }),
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .focusRequester(focusRequester)
                                        .background(Color.Transparent)
                                )

                                LaunchedEffect(Unit) {
                                    Timber.d("focusRequester.requestFocus()")
                                    focusRequester.requestFocus()
                                }

                            }

                            HorizontalDivider(thickness = 1.px.dp, color = Color(0,0,0).copy(alpha = 0.38f))
                        }
                    }
                }

                Spacer(Modifier.weight(1f))

                // Read & Cancel & OK
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(88.px.dp),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // Read
                    TextButton(
                        modifier = Modifier
                            .clip(RoundedCornerShape(24.px.dp))
                            .background(Color(243,205,81))
                            .size(68.px.dp, 40.px.dp),
                        onClick = {
                            Timber.d("Read Clicked")
                            onClickRead()
                        }
                    ) {
                        Text(
                            text = "Read",
                            style = RobotoTypography.labelLarge,
                            fontWeight = FontWeight.Normal,
                            fontSize = 14.px.sp,
                            color = Color.Black
                        )
                    }

                    Spacer(Modifier.weight(1f))

                    // Cancel
                    TextButton(
                        modifier = Modifier
                            .size(68.px.dp, 40.px.dp),
                        onClick = {
                            Timber.d("onLoadClick")
                            onClickCancel()
                        }
                    ) {
                        Text(
                            text = stringResource(R.string.cancel),
                            style = RobotoTypography.labelLarge,
                            fontWeight = FontWeight.Normal,
                            fontSize = 14.px.sp,
                            color = Color.Black
                        )
                    }

                    // Set
                    TextButton(
                        modifier = Modifier
                            .clip(RoundedCornerShape(24.px.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colorStops = arrayOf(
                                        0.0f to Color(47, 51,57),
                                        1.0f to Color(83, 88, 97),
                                    )
                                )
                            )
                            .border(
                                width = 1.5.px.dp,
                                brush = Brush.linearGradient(
                                    colorStops = arrayOf(
                                        0.0f to Color(92, 99,107),
                                        1.0f to Color(34, 37, 40),
                                    )
                                ),
                                shape = RoundedCornerShape(24.px.dp)
                            )
                            .dropShadow(
                                shape = RoundedCornerShape(24.px.dp),
                                color = Color(243,205,81).copy(alpha = 0.2f),
                                blur = 3.5.px.dp,
                                offsetX = 0.px.dp,
                                offsetY = 0.px.dp,
                                spread = 0.px.dp
                            )
                            .dropShadow(
                                shape = RoundedCornerShape(24.px.dp),
                                color = Color(0,0,0).copy(alpha = 0.1f),
                                blur = 1.75.px.dp,
                                offsetX = 0.px.dp,
                                offsetY = 1.75.px.dp,
                                spread = 0.px.dp
                            )
                            .size(68.px.dp, 40.px.dp),
                        onClick = {
                            Timber.d("Ok Clicked")
                            performSetClick()
                        }
                    ) {
                        Text(
                            text = "Set",
                            style = RobotoTypography.labelLarge,
                            fontWeight = FontWeight.Normal,
                            fontSize = 14.px.sp,
                            color = Color.White
                        )
                    }
                }

            }
        }
    }
}

@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 PreviewRefer1Popup(
    /*
    mainViewModel:MainViewModel = MainViewModel(
        preferenceRepository = PreferenceRepository(LocalContext.current),
        serialPortRepository = SerialPortRepository.createWithFakeRepository(),
        databaseRepository = DatabaseRepository(RamanDatabaseService(RamanDatabase.getInstance(LocalContext.current))),
        dispatcherProvider = DefaultDispatcherProvider(),
        applicationContext = LocalContext.current
    )
    */
) {
    Box(modifier = Modifier.fillMaxSize().background(Color.White)) {
        Refer1Popup(
            title = stringResource(R.string.energy_detect_refer1_title),
        )
    }
}
