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

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.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.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.Color
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.MAX_TEMP_DECIMAL_DIGIT
import com.laseroptek.raman.const.MAX_TEMP_INT_DIGIT
import com.laseroptek.raman.const.MAX_TEMP_VALUE
import com.laseroptek.raman.data.datasource.db.RamanDatabase
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.fullscreen.FullScreen
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.ext.dropShadow
import com.laseroptek.raman.utils.ext.px
import timber.log.Timber

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FloatPopup(
    title: String = stringResource(R.string.lamp_total_count_title),
    count: Float = 0.0f,
    maxIntegerDigits: Int = MAX_TEMP_INT_DIGIT, // e.g., for 100.0, this would be 3
    maxDecimalDigits: Int = MAX_TEMP_DECIMAL_DIGIT,  // e.g., for one decimal place, this is 1
    maxValue: Float = MAX_TEMP_VALUE,
    onClick: (Boolean, Float) -> Unit = { _, _ -> },
) {
    val context = LocalContext.current
    var textFieldValue by remember {
        mutableStateOf(
            // 2. Initialize TextFieldValue with the text and set the cursor to the end.
            TextFieldValue(
                text = count.toString(),
                selection = TextRange(count.toString().length) // This places the cursor at the end
            )
        )
    }
    val focusManager = LocalFocusManager.current
    val focusRequester = remember { FocusRequester() }

    val performOkClick = remember@{
        val text = textFieldValue.text

        if (text.isEmpty() || text == "." || text.endsWith(".")) { // Check for incomplete input
            Toast.makeText(context, "Invalid Number", Toast.LENGTH_SHORT).show()
            return@remember
        }

        val newFloat = text.toFloat()
        if (newFloat > maxValue) {
            Toast.makeText(context, "Input Number exceeded max value ${maxValue}", Toast.LENGTH_SHORT).show()
            return@remember
        }

        focusManager.clearFocus()
        Timber.d("OK action performed with count: ${newFloat}")
        onClick(true, newFloat)
    }

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

        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 100.px.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            Column(
                modifier = Modifier
                    .size(312.px.dp, 216.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
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(62.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,
                    )
                }

                // Text
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.px.dp)
                        .clip(RoundedCornerShape(4.px.dp))
                        .border(
                            width = 1.px.dp,
                            Color.Black.copy(alpha = 0.38f),
                            shape = RoundedCornerShape(4.px.dp)
                        )
                        .background(Color(245, 245, 245))
                    //.padding(10.px.dp)
                ) {
                    OutlinedTextField(
                        value = textFieldValue,
                        onValueChange = { newTextFieldValue ->
                            val newText = newTextFieldValue.text

                            val regex = """^\d{0,$maxIntegerDigits}(\.\d{0,$maxDecimalDigits})?$""".toRegex()

                            if (newText.isEmpty() || regex.matches(newText)) {
                                textFieldValue = newTextFieldValue
                            } else {
                                Toast.makeText(
                                    context,
                                    "Invalid float format or length exceeded.",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        },
                        //label = { Text("Float") },
                        keyboardOptions = KeyboardOptions(
                            keyboardType = KeyboardType.Number, // Use Number for decimals
                            imeAction = ImeAction.Done,
                        ),
                        singleLine = true,
                        keyboardActions = KeyboardActions(onDone = {
                            performOkClick()
                        }),
                        modifier = Modifier
                            .fillMaxSize()
                            .focusRequester(focusRequester)
                    )

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

                // Divider
                HorizontalDivider(
                    modifier = Modifier,
                    thickness = 0.5.px.dp,
                    color = Color.LightGray
                )

                Spacer(Modifier.weight(1f))

                // Cancel & OK
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(88.px.dp)
                        .padding(start = 10.px.dp, end = 10.px.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // Cancel
                    TextButton(
                        modifier = Modifier
                            .size(68.px.dp, 40.px.dp),
                        onClick = {
                            Timber.d("onLoadClick")
                            onClick(false, 0.0f)
                        }
                    ) {
                        Text(
                            text = stringResource(R.string.cancel),
                            style = RobotoTypography.labelLarge,
                            fontWeight = FontWeight.Normal,
                            fontSize = 14.px.sp,
                            color = Color.Black
                        )
                    }

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

            }
        }

    }
}

@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 PreviewFloatPopup(
    mainViewModel:MainViewModel = MainViewModel(
        preferenceRepository = PreferenceRepository(LocalContext.current),
        serialPortRepository = SerialPortRepository.createWithFakeRepository(),
        databaseRepository = DatabaseRepository(RamanDatabaseService(RamanDatabase.getInstance(LocalContext.current))),
        dispatcherProvider = DefaultDispatcherProvider(),
        applicationContext = LocalContext.current
    )
) {
    FloatPopup(
        //mainViewModel = mainViewModel
        title = stringResource(R.string.lamp_total_count_title),
        count = 123.4f
    )
}
