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


import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.foundation.layout.Arrangement
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
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.ui.theme.RobotoTypography
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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import timber.log.Timber


@Composable
fun RepetitionVoltageControlView(
    modifier: Modifier = Modifier,
    onClickDtoV: () -> Unit = {},
    onClickVtoD: () -> Unit = {},
    onClickUp: () -> Unit = {},
    onClickUpLongPress: () -> Unit = {},
    onClickDown: () -> Unit = {},
    onClickDownLongPress: () -> Unit = {},
) {
    val scope = rememberCoroutineScope()

    //val currentViewConfiguration = LocalViewConfiguration.current
    val customPressTimeout = 1000L // Desired long press duration in milliseconds (e.g., 1 second)

    //var longPressed by remember { mutableStateOf(false) }

    // Create a custom ViewConfiguration, remembering it to avoid recreation on recomposition
    /*
    val customViewConfiguration = remember(currentViewConfiguration) {
        object : ViewConfiguration by currentViewConfiguration { // Delegate to the current one
            override val longPressTimeoutMillis: Long = customPressTimeout
            // You can also override other properties like doubleTapTimeoutMillis if needed
            // override val doubleTapTimeoutMillis: Long = customDoubleTapTimeout
        }
    }
    */

    Column(
        modifier = modifier
            .background(Color.Transparent),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Row {
            // left (D->V, D<-V)
            Column(modifier = Modifier
                .fillMaxSize()
                .weight(1f),
                verticalArrangement = Arrangement.Bottom,
            ) {
                //Spacer(modifier = Modifier.weight(1f))

                // D->V
                Row(
                    Modifier
                        .noRippleClickable(onClick = onClickDtoV)
                        .fillMaxWidth()
                        .height(32.px.dp)
                        .clip(RoundedCornerShape(16.px.dp))
                        .background(Color.Black),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "D ",
                        color = Color.White,
                        style = RobotoTypography.bodyMedium,
                        fontWeight = FontWeight.ExtraLight,
                        fontSize = 14.px.sp,
                    )
                    Image(
                        painter = painterResource(id = R.drawable.ic_arrow_right),
                        contentDescription = null,
                        modifier = Modifier.size(18.px.dp),
                        contentScale = ContentScale.FillBounds,
                        colorFilter = ColorFilter.tint(Color.White)
                    )
                    Text(
                        text = " V",
                        color = Color.White,
                        style = RobotoTypography.bodyMedium,
                        fontWeight = FontWeight.ExtraLight,
                        fontSize = 14.px.sp,
                    )
                }
                Spacer(modifier = Modifier.height(8.px.dp))

                // D<-V
                Row(
                    Modifier
                        .noRippleClickable(onClick = onClickVtoD)
                        .fillMaxWidth()
                        .height(32.px.dp)
                        .clip(RoundedCornerShape(16.px.dp))
                        .background(Color.Black),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "D ",
                        color = Color.White,
                        style = RobotoTypography.bodyMedium,
                        fontWeight = FontWeight.ExtraLight,
                        fontSize = 14.px.sp,
                    )
                    Image(
                        painter = painterResource(id = R.drawable.ic_arrow_left),
                        contentDescription = null,
                        modifier = Modifier.size(18.px.dp),
                        contentScale = ContentScale.FillBounds,
                        colorFilter = ColorFilter.tint(Color.White)
                    )
                    Text(
                        text = " V",
                        color = Color.White,
                        style = RobotoTypography.bodyMedium,
                        fontWeight = FontWeight.ExtraLight,
                        fontSize = 14.px.sp,
                    )
                }

            }

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

            // right (Up, Down)
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .weight(1f),
                verticalArrangement = Arrangement.Bottom,
            ) {
                //Spacer(modifier = Modifier.weight(1f))

                // Up
                //CompositionLocalProvider(LocalViewConfiguration provides customViewConfiguration) {
                    Row(
                        Modifier
                            //.noRippleClickable(onClick = onClickUp)
                            .pointerInput(Unit) { // pass `Unit` or any key that, when changed, should reset the gesture detector
                                awaitEachGesture {
                                    var longPressOccurred = false

                                    awaitFirstDown()
                                    val job = scope.launch(Dispatchers.Default) {
                                        delay(customPressTimeout)

                                        longPressOccurred = true

                                        // Long press detected
                                        while (true) {
                                            Timber.d("Long press detected, starting repeating timer...")
                                            onClickUpLongPress.invoke()
                                            delay(300) // A responsive 300ms interval
                                        }
                                    }
                                    waitForUpOrCancellation()
                                    if (job.isActive) {
                                        job.cancel()

                                        // If the job is still active, it means it was a short press
                                        if (!longPressOccurred) {
                                            Timber.d("Short press detected.")
                                            onClickUp.invoke()
                                        } else {
                                            Timber.d("Up event after long press. Short press ignored.")
                                        }
                                    }
                                }
                            }
                            .fillMaxWidth()
                            .height(32.px.dp)
                            .border(
                                2.dp,
                                color = Color(70, 70, 70),
                                shape = RoundedCornerShape(10.px.dp)
                            )
                            .clip(RoundedCornerShape(10.px.dp))
                            .background(
                                brush = Brush.verticalGradient(
                                    colorStops = arrayOf(
                                        0.0f to Color(250, 250, 250),
                                        0.5f to Color(198, 198, 198),
                                        1.0f to Color(250, 250, 250),
                                    )
                                )
                            )
                            .dropShadow(
                                shape = RoundedCornerShape(0.px.dp),
                                color = Color(0, 0, 0).copy(alpha = 0.14f),
                                blur = 7.px.dp,
                                offsetY = 5.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            )
                            .innerShadow(
                                shape = RoundedCornerShape(0.px.dp),
                                color = Color(255, 255, 255),
                                blur = 1.px.dp,
                                offsetY = 4.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            ),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_up),
                            contentDescription = null,
                            modifier = Modifier.size(30.px.dp, 27.px.dp),
                            colorFilter = Color.Black.let { ColorFilter.tint(it) }
                        )
                    }
                //}


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

                // Down
                //CompositionLocalProvider(LocalViewConfiguration provides customViewConfiguration) {
                    Row(
                        Modifier
                            .pointerInput(Unit) {
                                awaitEachGesture {
                                    var longPressOccurred = false

                                    awaitFirstDown()
                                    val job = scope.launch(Dispatchers.Default) {
                                        delay(customPressTimeout)
                                        // Long press detected
                                        longPressOccurred = true

                                        while (true) {
                                            Timber.d("Long press detected, starting repeating timer...")
                                            onClickDownLongPress.invoke()
                                            delay(300) // A responsive 300ms interval
                                        }
                                    }
                                    waitForUpOrCancellation()
                                    if (job.isActive) {
                                        job.cancel()
                                        // If the job is still active, it means it was a short press
                                        Timber.d("Short press detected.")
                                        if (!longPressOccurred) {
                                            Timber.d("Short press detected.")
                                            onClickDown.invoke()
                                        } else {
                                            Timber.d("Up event after long press. Short press ignored.")
                                        }
                                    }
                                }
                            }
                            .fillMaxWidth()
                            .height(32.px.dp)
                            .border(
                                2.dp,
                                color = Color(70, 70, 70),
                                shape = RoundedCornerShape(10.px.dp)
                            )
                            .clip(RoundedCornerShape(10.px.dp))
                            .background(
                                brush = Brush.verticalGradient(
                                    colorStops = arrayOf(
                                        0.0f to Color(250, 250, 250),
                                        0.5f to Color(198, 198, 198),
                                        1.0f to Color(250, 250, 250),
                                    )
                                )
                            )
                            .dropShadow(
                                shape = RoundedCornerShape(0.px.dp),
                                color = Color(0, 0, 0).copy(alpha = 0.14f),
                                blur = 7.px.dp,
                                offsetY = 5.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            )
                            .innerShadow(
                                shape = RoundedCornerShape(0.px.dp),
                                color = Color(255, 255, 255),
                                blur = 1.px.dp,
                                offsetY = 4.px.dp,
                                offsetX = 0.px.dp,
                                spread = 0.px.dp
                            ),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_down),
                            contentDescription = null,
                            modifier = Modifier.size(30.px.dp, 27.px.dp),
                            colorFilter = Color.Black.let { ColorFilter.tint(it) }
                        )
                    }
                //}
            }
        }
    }
}


@Preview(
    uiMode = Configuration.UI_MODE_NIGHT_NO,
    showBackground = false,
    device = "spec:width=640dp,height=240dp,dpi=150,isRound=false,chinSize=0dp,orientation=landscape"
)
@Composable
fun PreviewRepetitionVoltageControlView() {
    Row {
        RepetitionVoltageControlView()
    }
}