package com.vpn.fastestvpnservice.screens.bottomNavBarScreens

import android.content.res.Configuration
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
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.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableFloatStateOf
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.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontStyle
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.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.vpn.fastestvpnservice.R
import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
import com.vpn.fastestvpnservice.sealedClass.Screen
import com.vpn.fastestvpnservice.viewmodels.AccountViewModel
import kotlinx.coroutines.delay

//var LocalLoggedOut = staticCompositionLocalOf<Boolean> { false }

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Account(navHostController: NavHostController,
            settingsNavHostController: NavHostController)
{
    var isLoggedOut by remember { mutableStateOf(false) }
    var isDelete by remember { mutableStateOf(false) }

    val context = LocalContext.current
    val basePreferenceHelper = BasePreferenceHelper(context)

    val accountViewModel: AccountViewModel = viewModel()

    Box(modifier = Modifier
        .background(MaterialTheme.colorScheme.background)
        .fillMaxSize()
//        contentAlignment = Alignment.Center

    ) {
        Column(
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.Start,
            modifier = Modifier
                .padding(start = 16.dp, end = 24.dp)
                .fillMaxSize()
        ) {
            Spacer(modifier = Modifier.height(60.dp))
            AddTextAccount(
                text = "Account",
                size = 28.sp,
                color = MaterialTheme.colorScheme.primary
            )
            AddRowAccount("Email:", basePreferenceHelper.getUser()?.userinfo?.email ?: "")
            AddRowAccount("Product:", basePreferenceHelper.getUser()?.product?.productName ?: "")
            AddRowAccount("Account Status:", basePreferenceHelper.getUser()?.product?.status ?: "")

            Surface(
                modifier = Modifier
                    .padding(top = 24.dp, bottom = 0.dp)
                    .height(1.dp)
                    .fillMaxWidth(),
                color = colorResource(id = R.color.gray_icon)
            ) {}

            AddRowAccountIcon(
                icon = painterResource(id = R.drawable.subscription3x),
                text = "Upgrade Subscription",
                onClick = {
                    navHostController.navigate(
                        Screen.Subscription.route
                    )
                }
            )
            AddRowAccountIcon(
                icon = painterResource(id = R.drawable.fav3x),
                text = "Favorite Servers",
                onClick = {
                    navHostController.navigate(
                        Screen.FavoriteServers.route
                    )
                }
            )
            AddRowAccountIcon(
                icon = painterResource(id = R.drawable.lock3x),
                text = "Change Password",
                onClick = {
                    navHostController.navigate(
                        Screen.ChangePassword.route
                    )
                }
            )
            AddRowAccountIcon(
                icon = painterResource(id = R.drawable.delete3x),
                text = "Delete Account",
                onClick = {
                    isDelete = true
                    Log.d("islogoutClicked?", "isDelete Yes")
                }
            )
            AddRowAccountIcon(
                icon = painterResource(id = R.drawable.logout3x),
                text = "Logout",
                onClick = {
                    isLoggedOut = true
                    Log.d("islogoutClicked?", "Yes")
                }
            )
        }

        if (isLoggedOut) {
            Log.d("islogoutClicked", "isLoggedOut$isLoggedOut")

            AlertDialog(
                onDismissRequest = { isLoggedOut = false },
                properties = DialogProperties(),
                modifier = Modifier
                    .fillMaxWidth()
                    .height(228.dp)
                ) {
                LogoutDialog("Logout Account",
                    "Are you sure to logout the account?",
                    onCancel = {
                        isLoggedOut = false
                    },
                    settingsNavHostController,
                    isLoggedOut,
                    isDelete,
                    basePreferenceHelper,
                    accountViewModel
                    )
            }
        }

        if (isDelete) {
            Log.d("islogoutClicked", "isDelete$isDelete")

            AlertDialog(
                onDismissRequest = { isDelete = false },
                properties = DialogProperties(),
                modifier = Modifier
                    .fillMaxWidth()
                    .height(228.dp)
            ) {
                LogoutDialog("Delete Account",
                    "Are you sure to delete the account?",
                    onCancel = { isDelete = false },
                    settingsNavHostController,
                    isLoggedOut,
                    isDelete,
                    basePreferenceHelper,
                    accountViewModel
                    )
            }
        }

        if (accountViewModel.liveDataLogoutStatus.value == true) {
            var progress by remember { mutableFloatStateOf(0.1F) }

            LaunchedEffect(key1 = Unit) {
                for (i in 1..100) {
                    progress = i.toFloat()/100F
                    delay(100)
                }
            }

            CircularProgressIndicator(
                progress = { progress },
                modifier = Modifier
                    .align(Alignment.Center)
                    .size(50.dp),
                color = colorResource(id = R.color.yellow_text),
                strokeWidth = 5.dp,
            )
        }

        val logoutResponse = accountViewModel.liveDataLogout.observeAsState().value
        logoutResponse?.let {
            accountViewModel.setLogoutStatus(false)
            if (it) {
                Log.d("test_api_response","Logout live: $logoutResponse")
                basePreferenceHelper.setLoggedInState(false)
                basePreferenceHelper.clearAllData()
                settingsNavHostController.popBackStack()
                settingsNavHostController.navigate(Screen.Started.route)
            }
            else {
                Log.d("test_api_response","Logout false: $logoutResponse")
                accountViewModel.mutableLiveDataLogoutStatus.value = false
                Toast.makeText(context, logoutResponse.toString(), Toast.LENGTH_SHORT).show()
            }
            accountViewModel.mutableLiveDataLogout.value = null
        }

        val deleteResponse = accountViewModel.liveDataDelete.observeAsState().value
        deleteResponse?.let {
            accountViewModel.setLogoutStatus(false)
            if (it.status) {
                Log.d("test_api_response","Delete live: ${deleteResponse.status}")
                basePreferenceHelper.setLoggedInState(false)
                basePreferenceHelper.clearAllData()
                settingsNavHostController.popBackStack()
                settingsNavHostController.navigate(Screen.Started.route)
            }
            else {
                Log.d("test_api_response","Delete false: ${deleteResponse.status}")
                accountViewModel.mutableLiveDataDeleteStatus.value = false
                Toast.makeText(context, deleteResponse.status.toString(), Toast.LENGTH_SHORT).show()
            }
            accountViewModel.mutableLiveDataDelete.value = null
        }
    }
}

@Composable
fun ColumnScope.AddTextAccount(text: String, size: TextUnit, color: Color) {
    Text(
        text = text,
        style = TextStyle(
            fontSize = size,
            color = color,
            textAlign = TextAlign.Center,
            fontStyle = FontStyle.Normal,
            fontWeight = FontWeight.Medium,
        ),
    )
}

@Composable
fun ColumnScope.AddRowAccount(title: String, subTitle: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 16.dp)
            .background(Color.Transparent)
            .height(18.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Surface(
            modifier = Modifier.padding(start = 0.dp),
            color = Color.Transparent
        ) {
            Text(text = title,
                style = TextStyle(
                    color = MaterialTheme.colorScheme.primary,
                    fontSize = 14.sp,
                    fontStyle = FontStyle.Normal,
                    fontWeight = FontWeight.Medium
                ),
                maxLines = 1,
                modifier = Modifier
                    .padding(start = 10.dp, end = 0.dp)
                    .weight(1f)
            )
        }
//        Spacer(modifier = Modifier.weight(1f))

        Surface(
            modifier = Modifier
                .padding(start = 0.dp)
                .align(Alignment.CenterVertically),
            color = Color.Transparent

        ) {
            Text(text = subTitle,
                style = TextStyle(
                    color = MaterialTheme.colorScheme.primary,
                    fontSize = 14.sp,
                    fontStyle = FontStyle.Normal,
                    fontWeight = FontWeight.Medium,
                    textAlign = TextAlign.Right,
                ),
                maxLines = 1,
                modifier = Modifier
                    .padding(start = 0.dp, end = 0.dp)
                    .weight(1f)
                    .alpha(0.6F)
            )
        }

    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ColumnScope.AddRowAccountIcon(
    icon: Painter,
    text: String,
    onClick : () -> Unit
) {

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 33.dp)
            .background(Color.Transparent)
            .height(30.dp)
            .pointerInput(Unit) {
                detectTapGestures {
                    onClick()
                }
            },
        horizontalArrangement = Arrangement.Start,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Surface(
            modifier = Modifier.padding(start = 0.dp),
            color = Color.Transparent
        ) {
            Image(
                painter = icon,
                contentDescription = "World",
                modifier = Modifier
                    .padding(start = 0.dp)
                    .size(24.dp)
                    .weight(1f),
                colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.primary)
            )
        }
        Surface(
            modifier = Modifier.padding(start = 0.dp),
            color = Color.Transparent
        ) {
            Text(text = text,
                style = TextStyle(
                    color = MaterialTheme.colorScheme.primary,
                    fontSize = 16.sp,
                    fontStyle = FontStyle.Normal,
                    fontWeight = FontWeight.Medium
                ),
                maxLines = 2,
                modifier = Modifier
                    .padding(start = 20.dp, end = 0.dp)
                    .weight(1f)
            )
        }
        Spacer(modifier = Modifier.weight(1f))
        Surface(
            modifier = Modifier
                .padding(start = 15.dp)
                .align(Alignment.CenterVertically),
            color = Color.Transparent
        ) {
            Image(
                painter = painterResource(id = R.drawable.frontarrow3x),
                contentDescription = "Front_Arrow",
                modifier = Modifier
                    .padding(start = 0.dp, end = 5.dp)
                    .size(10.dp, 18.dp)
                    .weight(1f),
                colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.primary)
            )
        }


    }


}

@Composable
fun BoxScope.LogoutDialog(
    title: String,
    desc: String,
    onCancel : () -> Unit,
    settingsNavHostController: NavHostController,
    isLogout: Boolean,
    isDelete: Boolean,
    basePreferenceHelper: BasePreferenceHelper,
    accountViewModel: AccountViewModel
) {

    Surface(
        color = colorResource(id = R.color.white),
        modifier = Modifier
            .background(Color.Transparent)
            .fillMaxWidth()
        ,
        shape = RoundedCornerShape(18.dp)
    ) {
        Column(
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier
                .background(MaterialTheme.colorScheme.onPrimary)
        ) {
            Log.d("islogoutClicked", "AlertDialog")

            Text(text = title,
                style = TextStyle(
                    fontSize = 18.sp,
                    textAlign = TextAlign.Center,
                    fontWeight = FontWeight.Medium,
                    color = MaterialTheme.colorScheme.primary
                ),
                modifier = Modifier.padding(top = 45.dp)
            )
            Text(text = desc,
                style = TextStyle(
                    fontSize = 18.sp,
                    textAlign = TextAlign.Center,
                    color = MaterialTheme.colorScheme.primary,
                    lineHeight = 30.sp
                ),
                maxLines = 2,
                modifier = Modifier.padding(top = 26.dp)
            )
            Row (
                modifier = Modifier
                    .padding(top = 34.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Bottom
            ) {
                Button(
                    onClick = {
                        Log.d("test_button", "No")
                        onCancel()
//                                    navHostController.popBackStack()
//                                    navHostController.navigate(Screen.Login.route)
                    },
                    modifier = Modifier
                        .padding(
                            start = 15.dp, end = 5.dp,
                            bottom = 0.dp, top = 0.dp
                        )
                        .background(colorResource(id = R.color.transparent))
                        .weight(1F)
                        .height(52.dp),

                    shape = RoundedCornerShape(15.dp),
                    colors = ButtonDefaults.buttonColors(
                        contentColor = colorResource(id = R.color.white),
                        containerColor = colorResource(id = R.color.light_blue),
                    ),
                )
                {
                    Text(text = "No", fontSize = 20.sp)
                    Log.d("test_button", "RowScope")
                }

                Button(
                    onClick = {
                        Log.d("test_button", "Yes")

                        if (isLogout) {
                            Log.d("test_api_response","Logout click = $isLogout")
                            accountViewModel.setLogoutStatus(true)
                            accountViewModel.logout()
                            onCancel()
                        }

                        if (isDelete) {
                            Log.d("test_api_response","Delete click = $isDelete")
                            accountViewModel.setLogoutStatus(true)
                            accountViewModel.deleteAccount()
                            onCancel()
                        }

                    },
                    modifier = Modifier
                        .padding(
                            start = 5.dp, end = 15.dp,
                            bottom = 0.dp, top = 0.dp
                        )
                        .background(colorResource(id = R.color.transparent))
                        .weight(1F)
                        .height(52.dp),
                    shape = RoundedCornerShape(15.dp),
                    colors = ButtonDefaults.buttonColors(
                        contentColor = colorResource(id = R.color.white),
                        containerColor = colorResource(id = R.color.red),
                    ),
//                                border = BorderStroke(2.dp,
//                                    colorResource(id = R.color.gray_icon))
                )
                {
                    Text(text = "Yes", fontSize = 20.sp)
                    Log.d("test_button", "RowScope")

//                    val logoutResponse = accountViewModel.liveDataLogout.observeAsState().value
//                    if (logoutResponse == true) {
//                        accountViewModel.setLogoutStatus(false)
//                        Log.d("test_api_response","Logout live: $logoutResponse")
//                        basePreferenceHelper.setLoggedInState(false)
//                        settingsNavHostController.popBackStack()
//                        settingsNavHostController.navigate(Screen.Started.route)
//                    }
//                    else {
////                        accountViewModel.setLogoutStatus(false)
////                        onCancel()
//                    }
                }
            }
        }

    }
}

@Preview
@Composable
fun AccountPreview() {
    Account(rememberNavController(), rememberNavController())
}

@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun AccountPreviewDark() {
    Account(rememberNavController(), rememberNavController())
}