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

import android.content.res.Configuration
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.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
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.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
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 androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.laseroptek.raman.R
import com.laseroptek.raman.navigation.LockNavigation
import com.laseroptek.raman.ui.common.button.ButtonWithHIconAndText
import com.laseroptek.raman.ui.common.fullscreen.FullScreenDialog
import com.laseroptek.raman.ui.theme.PretendardTypography
import com.laseroptek.raman.ui.theme.RobotoTypography
import com.laseroptek.raman.utils.ext.px
import kotlinx.coroutines.delay
import timber.log.Timber
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LockScreen(
    mainNavController: NavHostController = rememberNavController(),
    lockViewModel:LockViewModel = hiltViewModel<LockViewModel>()
) {
    val focusManager = LocalFocusManager.current

    var showPopup by remember { mutableStateOf( true ) }
    var navigation by rememberSaveable { mutableStateOf(LockNavigation.Enter) }

    // Get Current Time
    val currentDateTime = remember { mutableStateOf(LocalDateTime.now()) }
    val pinNumber = remember { mutableStateOf("") }

    val dateFormatter = DateTimeFormatter.ofPattern("EEE, MMM dd, yyyy")
    val timeFormatter = DateTimeFormatter.ofPattern("hh:mm a")

    val formattedDate = currentDateTime.value.format(dateFormatter)
    val formattedTime = currentDateTime.value.format(timeFormatter)

    val modifierFullScreen = Modifier.then(
        if (navigation == LockNavigation.Lock) {
            Modifier
                .fillMaxSize()
                .background(color = Color.White) //.padding(top = 93.px.dp)
        } else {
            Modifier
                .size(867.px.dp, 1032.px.dp)
                .background(Color.Transparent)
        }
    )

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

    LaunchedEffect(Unit) {
        currentDateTime.value = LocalDateTime.now()
        delay(60*1000) // Delay for 1 minute

    }

    //FullScreenPopup(showPopup = showLockPopup) {
    if (showPopup) {
        FullScreenDialog(backgroundColor = Color(120,120,120)) {
            //FullScreen(backgroundColor = Color.Black) {
            Box(
                modifier = modifierFullScreen,
                contentAlignment = Alignment.Center
            ) {
                when (navigation) {
                    LockNavigation.Enter -> {
                        Timber.d("Enter")
                        PinLock(
                            title = stringResource(id = R.string.lock_title),
                            lockState = LockNavigation.Enter,
                            pinNumber = pinNumber,
                            onClick = { ok ->
                                if (ok) {
                                    // on ok check created password and go to confirm
                                    Timber.d("pinNumber: ${pinNumber}")
                                    navigation = LockNavigation.EnterConfirm
                                } else {
                                    // on click cancel -> exit to main screen
                                    showPopup = false

                                    // goback
                                    mainNavController.popBackStack()
                                }
                            }
                        )
                    }

                    LockNavigation.EnterConfirm -> {
                        Timber.d("EnterConfirm")
                        PinLock(
                            title = "Confirm the password for device lock",
                            lockState = LockNavigation.EnterConfirm,
                            pinNumber = pinNumber,
                            onClick = { ok ->
                                if (ok) {
                                    // go to lock
                                    Timber.d("pinNumber: ${pinNumber}")
                                    navigation = LockNavigation.Lock
                                } else {
                                    // on click cancel -> goto Enter
                                    navigation = LockNavigation.Enter
                                }
                            }
                        )
                    }

                    LockNavigation.Lock -> {
                        Timber.d("Lock")
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center,
                            modifier = Modifier
                                .fillMaxSize()
                                .background(Color.Black)
                        ) {
                            // Thu, Feb 29, 2024
                            Text(
                                text = formattedDate,
                                style = RobotoTypography.bodyMedium,
                                fontWeight = FontWeight.Light,
                                fontSize = 16.px.sp,
                                color = Color.White,
                                textAlign = TextAlign.Center,
                            )

                            // hh:mm am
                            Text(
                                text = formattedTime,
                                style = RobotoTypography.bodyMedium,
                                fontWeight = FontWeight.Light,
                                fontSize = 34.px.sp,
                                color = Color.White,
                                textAlign = TextAlign.Center,
                            )

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

                            // lock icon
                            Image(
                                painter = painterResource(id = R.drawable.ic_lock_screen),
                                contentDescription = null,
                                modifier = Modifier.size(46.px.dp)
                            )

                            // text device is locked.
                            Text(
                                text = "Device is locked",
                                style = PretendardTypography.bodyMedium,
                                fontWeight = FontWeight.Light,
                                fontSize = 16.px.sp,
                                color = Color(243,205,81),
                                textAlign = TextAlign.Center,
                            )

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

                            // button with icon
                            ButtonWithHIconAndText(
                                modifier = Modifier
                                    .size(240.px.dp, 40.px.dp)
                                    .border(
                                        width = 1.px.dp,
                                        shape = RoundedCornerShape(100.px.dp),
                                        color = Color(215, 167, 10),
                                    ),
                                text = stringResource(R.string.unlock),
                                style = RobotoTypography.bodySmall,
                                fontSize = 14.px.sp,
                                textColor = Color(215, 167, 10),
                                backgroundColor = Color.Transparent,
                                roundedCornerShape = RoundedCornerShape(100.px.dp),
                                leadingIcon = {
                                    Image(
                                        modifier = Modifier.size(18.px.dp),
                                        painter = painterResource(id = R.drawable.ic_unlock),
                                        contentDescription = null,
                                    )
                                },
                                onClick = {
                                    navigation = LockNavigation.ExitConfirm
                                }
                            )

                            Spacer(Modifier.height(100.px.dp))
                        }
                    }

                    LockNavigation.ExitConfirm -> {
                        Timber.d("ExitConfirm")
                        PinLock(
                            title = "Confirm the password to exit Lock",
                            lockState = LockNavigation.ExitConfirm,
                            pinNumber = pinNumber,
                            onClick = { ok ->
                                if (ok) {
                                    Timber.d("pinNumber: ${pinNumber}")
                                    showPopup = false
                                    // goback
                                    mainNavController.popBackStack()
                                } else {
                                    // on click cancel back to Lock Screen Again
                                    navigation = LockNavigation.Lock
                                }
                            }
                        )
                    }
                }
            }
        }
    }

}


@Preview(
    uiMode = Configuration.UI_MODE_NIGHT_NO,
    showBackground = false,
    device = "spec:width=1920dp,height=1080dp,dpi=150,isRound=false,chinSize=0dp,orientation=landscape"
)
@Composable
fun PreviewLockScreen() {
    LockScreen()
}
