package com.laseroptek.raman.ui.screens.config.language

import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.ExperimentalMaterial3Api
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.platform.LocalContext
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.core.app.ActivityCompat.recreate
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import com.laseroptek.raman.R
import com.laseroptek.raman.ui.common.fullscreen.FullScreen
import com.laseroptek.raman.ui.theme.RobotoTypography
import com.laseroptek.raman.utils.SharedPreferenceHelper
import com.laseroptek.raman.utils.ext.dropShadow
import com.laseroptek.raman.utils.ext.getActivity
import com.laseroptek.raman.utils.ext.px
import timber.log.Timber

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LanguageView(
    modifier: Modifier = Modifier,
    languageViewModel: LanguageViewModel = hiltViewModel<LanguageViewModel>(),
    //showLanguageScreen: MutableState<Boolean> = mutableStateOf(false),
    //mainViewModel: MainViewModel = hiltViewModel<MainViewModel>(),
    title: String = stringResource(R.string.language),
    onClick: (Boolean) -> Unit = {},
) {
    val context = LocalContext.current
    val activity= context.getActivity()

    var currentLanguage: String = ""
    val selectedLanguage by languageViewModel.selectedLanguage.collectAsState()

    val selectedIndex = remember { mutableStateOf( if (selectedLanguage == "en") 0 else 1) }
    val languageList = listOf("en", "ko")

    LaunchedEffect(Unit) {
        currentLanguage = SharedPreferenceHelper.getString(context, "language", "en") ?: "en"
        Timber.d("attachBaseContext: language: ${selectedLanguage}")

        languageViewModel.setSelectedLanguage(selectedLanguage)
    }

    FullScreen {
        Column(
            modifier = modifier
                .size(312.px.dp, 272.px.dp)
                .clip(RoundedCornerShape(28.px.dp))
                .background(Color.White)
                .dropShadow(
                    shape = RoundedCornerShape(28.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(28.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
                ),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            // Title
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(60.px.dp)
                    .padding(start = 20.px.dp, end = 20.px.dp),
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically
            ){
                Text(
                    text = title,
                    style = RobotoTypography.headlineSmall,
                    fontWeight = FontWeight.ExtraLight,
                    fontSize = 22.px.sp,
                    color = Color.Black,
                    textAlign = TextAlign.Center,
                )
            }

            // English - Radio
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.px.dp)
                    .padding(start = 20.px.dp, end = 20.px.dp),
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically
            ){
                RadioButton(
                    selected = selectedIndex.value == 0,
                    onClick = {
                        languageViewModel.setSelectedLanguage("en")
                        selectedIndex.value = 0
                    }
                )
                Text(
                    text = stringResource(R.string.english),
                    style = RobotoTypography.headlineSmall,
                    fontWeight = FontWeight.ExtraLight,
                    fontSize = 14.px.sp,
                    color = Color.Black,
                    textAlign = TextAlign.Center,
                )
            }

            // Korean - Radio
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.px.dp)
                    .padding(start = 20.px.dp, end = 20.px.dp),
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically
            ){
                RadioButton(
                    selected = selectedIndex.value == 1,
                    onClick = {
                        selectedIndex.value = 1
                        languageViewModel.setSelectedLanguage("ko")
                    }
                )
                Text(
                    text = stringResource(R.string.korean),
                    style = RobotoTypography.headlineSmall,
                    fontWeight = FontWeight.ExtraLight,
                    fontSize = 14.px.sp,
                    color = Color.Black,
                    textAlign = TextAlign.Center,
                )
            }

            // 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("Cancel Clicked")
                        //showLanguageScreen = false
                        onClick.invoke(false)
                    }
                ) {
                    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("onClickOK")
                        Timber.d("currentLanguage: ${currentLanguage}")
                        Timber.d("selectedLanguage: ${selectedLanguage}")

                        if (currentLanguage != selectedLanguage) {
                            val selectedLanguage = languageList[selectedIndex.value]
                            Timber.d("language: ${selectedLanguage}")

                            //mainViewModel.setSelectedlanguage(selectedLanguage)

                            // Save a string
                            SharedPreferenceHelper.saveString(context, "language", selectedLanguage)

                            if (activity != null) {
                                // apply new language -> attchBaseContext will be called after restart
                                recreate(activity)
                            }
                        }
                        onClick.invoke(false)
                        return@TextButton
                    }
                ) {
                    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 = true,
    device = "spec:width=1280dp,height=720dp,dpi=150,isRound=false,chinSize=0dp,orientation=landscape"
)
@Composable
fun PreviewLanguageView(
    languageViewModel: LanguageViewModel = LanguageViewModel(
        /*
        preferenceRepository = PreferenceRepository(LocalContext.current),
        serialPortRepository = SerialPortRepository.createWithFakeRepository(),
        databaseRepository = DatabaseRepository(RamanDatabaseService(RamanDatabase.getInstance(LocalContext.current))),
        dispatcherProvider = DefaultDispatcherProvider(),
        applicationContext = LocalContext.current
        */
    )
) {
    //val showLanguageScreen = remember { mutableStateOf(true) }
    LanguageView(
        languageViewModel = languageViewModel
        //showLanguageScreen = showLanguageScreen,
        //mainViewModel = mainViewModel,
    )

    /* Theme, also colorScheme not working on Preview.
    MaterialTheme (
    colorScheme = LightColors // DarkColors
    ) {
    LanguageView(
    showLanguageScreen = showLanguageScreen,
    mainViewModel = mainViewModel,
    )
    */
}
