package com.laseroptek.raman.ui.screens.lock

import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.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.MutableState
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.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.laseroptek.raman.R
import com.laseroptek.raman.navigation.LockNavigation
import com.laseroptek.raman.ui.common.lock.OTPBox
import com.laseroptek.raman.ui.theme.RobotoTypography
import com.laseroptek.raman.utils.ext.dropShadow
import com.laseroptek.raman.utils.ext.px
import kotlinx.coroutines.delay
import timber.log.Timber

@SuppressLint("UnusedContentLambdaTargetStateParameter")
@Composable
fun PinLock(
    title: String = "",
    lockState: LockNavigation = LockNavigation.Enter,
    pinNumber: MutableState<String> = mutableStateOf(""),
    onClick: (Boolean) -> Unit,
    modifier: Modifier = Modifier,
) {
    var pin by remember { mutableStateOf("") }
    var animate by remember { mutableStateOf(false) }
    var autoShowKeyboard by remember { mutableStateOf(true) }

    LaunchedEffect(animate) {
        if (animate) {
            // After a short delay (enough for the animation to start),
            // reset the trigger.
            delay(100)
            animate = false
        }
    }

    DisposableEffect(Unit) {
        onDispose {
            Timber.d("MyComposable is being disposed!")
            autoShowKeyboard = false
        }
    }

    Box(
        modifier = modifier
            .fillMaxSize()
        , contentAlignment = Alignment.Center
    ) {
        Column(
            modifier = Modifier
                .size(448.px.dp, 580.px.dp)
            , horizontalAlignment = Alignment.CenterHorizontally
            , verticalArrangement = Arrangement.Center
        ) {
            // Pin Lock Box
            Column(
                modifier = Modifier
                    .size(448.px.dp, 280.px.dp)
                    .clip(RoundedCornerShape(28.px.dp))
                    .background(color = Color.White)
                    .dropShadow(
                        shape = RoundedCornerShape(28.px.dp),
                        color = Color(0, 0, 0).copy(alpha = 0.2f),
                        blur = 48.px.dp,
                        offsetX = 0.px.dp,
                        offsetY = 24.px.dp,
                        spread = 0.px.dp
                    )
                    .dropShadow(
                        shape = RoundedCornerShape(28.px.dp),
                        color = Color(0, 0, 0).copy(alpha = 0.1f),
                        blur = 6.px.dp,
                        offsetX = 0.px.dp,
                        offsetY = 3.px.dp,
                        spread = 0.px.dp
                    ),
                verticalArrangement = Arrangement.Top,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // Icon
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.px.dp),
                    verticalAlignment = Alignment.Bottom,
                    horizontalArrangement = Arrangement.Center
                ) {
                    Image(painter = painterResource(id = R.drawable.ic_lock_small),
                        contentDescription = null,
                        modifier = Modifier.size(24.px.dp)
                    )
                }

                // Title
                Row(modifier = Modifier
                    .fillMaxWidth()
                    .height(50.px.dp)
                    , verticalAlignment = Alignment.CenterVertically
                    , horizontalArrangement = Arrangement.Center
                ) {
                    Text(
                        text = title,
                        style = RobotoTypography.headlineSmall,
                        fontSize = 22.px.sp,
                        letterSpacing = 0.px.sp,
                        fontWeight = FontWeight.Normal,
                        color = Color.Black
                    )
                }

                // PinLock
                Box(
                    modifier = Modifier
                        .size(398.px.dp, 100.px.dp),
                    contentAlignment = Alignment.Center
                ) {
                    AnimatedContent(
                        targetState = animate,
                        transitionSpec = {
                            slideInHorizontally(
                                animationSpec = spring(dampingRatio = Spring.DampingRatioHighBouncy, stiffness = Spring.StiffnessHigh),
                                initialOffsetX = { fullWidth -> fullWidth }
                            ).togetherWith(
                                slideOutHorizontally(
                                    animationSpec = spring(dampingRatio = Spring.DampingRatioHighBouncy, stiffness = Spring.StiffnessHigh),
                                    targetOffsetX = { 0 }
                                )
                            )
                        },
                    ) {
                        OTPBox(
                            keyboardType = KeyboardType.NumberPassword,
                            pinLength = 6,
                            pinValue = pin,
                            onPinValueChanged = { newPin ->
                                Timber.d("onPinValueChanged: pin = ${newPin}")
                                pin = newPin
                            },
                            onDone = {
                                Timber.d("onDone")
                                when (lockState) {
                                    LockNavigation.Enter -> {
                                        if (pin.length == 6) {
                                            autoShowKeyboard = false
                                            pinNumber.value = pin
                                            onClick(true)
                                        } else {
                                            pin = ""
                                            animate = true
                                        }
                                    }
                                    else -> {
                                        if (pin == pinNumber.value) {
                                            autoShowKeyboard = false
                                            pinNumber.value = pin
                                            onClick(true)
                                        } else {
                                            pin = ""    // clear pin when not correct
                                            animate = true
                                        }
                                    }
                                }
                            },
                            autoShowKeyboard = autoShowKeyboard
                        )
                    }
                }

                Spacer(Modifier.weight(1f))

                // Cancel - Button
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.px.dp)
                ) {
                    Spacer(Modifier.weight(1f))

                    // Cancel - Button
                    TextButton(
                        modifier = Modifier
                            .size(width=80.px.dp, height=40.px.dp),
                        onClick = {
                            Timber.d("Cancel Clicked")
                            onClick(false)
                        }
                    ) {
                        Text(
                            text = stringResource(R.string.cancel),
                            style = RobotoTypography.titleMedium,
                            fontSize = 15.px.sp,
                            color = Color.Black
                        )
                    }

                    // OK - Button
                    TextButton(
                        modifier = Modifier
                            .size(width=68.px.dp, height=40.px.dp),
                        onClick = {
                            Timber.d("OK Clicked: ${pin}")
                            when (lockState) {
                                LockNavigation.Enter -> {
                                    if (pin.length == 6) {
                                        pinNumber.value = pin
                                        onClick(true)
                                    } else {
                                        pin = ""
                                        animate = true
                                    }
                                }
                                else -> {
                                    if (pin == pinNumber.value) {
                                        pinNumber.value = pin
                                        onClick(true)
                                    } else {
                                        pin = ""    // clear pin when not correct
                                        animate = true
                                    }
                                }
                            }
                        }
                    ) {
                        Text(
                            text = stringResource(R.string.ok),
                            style = RobotoTypography.titleMedium,
                            fontSize = 15.px.sp,
                            color = Color.Black
                        )
                    }
                }

                Spacer(Modifier.weight(1f))
            }

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