package com.jihe.punchnet.screen

import android.app.Activity.MODE_PRIVATE
import android.app.Activity.RESULT_CANCELED
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.net.VpnService
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
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.fillMaxHeight
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.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
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.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.jihe.punchnet.PunchnetService
import com.jihe.punchnet.PunchnetServiceArgument
import com.jihe.punchnet.R
import com.jihe.punchnet.RouteInfo
import com.jihe.punchnet.data.ButtonRepository
import com.jihe.punchnet.data.ButtonState
import com.jihe.punchnet.data.ButtonViewModel
import com.jihe.punchnet.data.RouteViewModel
import com.jihe.punchnet.data.ServiceViewModel
import com.jihe.punchnet.helper.PreferenceName
import com.jihe.punchnet.helper.getPreferenceString
import com.jihe.punchnet.helper.setPreferenceString
import kotlin.math.exp

data class HomeDropDownInfo(
    @DrawableRes val icon: Int,
    val name: String,
    val callback: (()->Unit)? = null,
)

@Composable
fun HomeDropdownMenu(
    showTokenDialog: MutableState<Boolean>,
) {
    var expanded by remember { mutableStateOf(false) }
    // var showTokenDialog by remember { mutableStateOf(false) }
    // val showSettingDialog by remember { mutableStateOf(false) }

    val context = LocalContext.current
    val homeItems = arrayOf(
        HomeDropDownInfo(
            R.drawable.tag,
            "修改token",
            {
                showTokenDialog.value = true
            }
        ),
        /*
        HomeDropDownInfo(
            R.drawable.preferences,
            "修改云端配置"
        )
         */
    )



    Box() {
        IconButton(
            interactionSource = remember { MutableInteractionSource() },
            modifier = Modifier.indication(
                interactionSource = remember { MutableInteractionSource() },
                indication = null,
            ),
            onClick = {
                expanded = true
            }
        ) {
            Icon(
                Icons.Default.Settings,
                contentDescription = "settings",
            )
        }
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = {expanded = !expanded}
        ) {
            homeItems.forEach { item ->
                DropdownMenuItem(
                    onClick = {
                        expanded = false
                        item.callback?.invoke()
                    },
                    text = {

                        Row (
                            verticalAlignment = Alignment.CenterVertically
                        ){
                            Icon(
                                painter = painterResource(item.icon),
                                modifier = Modifier.size(24.dp),
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.onBackground
                            )

                            Spacer(
                                modifier = Modifier.padding(start = 8.dp)
                            )

                            Text(text=item.name)
                        }

                    }
                )
            }
        }

    }
}

@Composable
fun HomeScreen(
    buttonViewModel: ButtonViewModel,
    serviceViewModel: ServiceViewModel,
    routeViewModel: RouteViewModel,
    // started: MutableState<Boolean>,
    modifier: Modifier = Modifier,
) {

    val context = LocalContext.current
    val tkPref = getPreferenceString(context, PreferenceName.PreferenceToken)

    var tokenvalue by remember {mutableStateOf(tkPref?:"")}

    val allroutes = routeViewModel.allRoutes.collectAsState(emptyList())
    val vpnLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult()
    ) {result ->
        when(result.resultCode) {
            RESULT_OK -> {
                // serviceViewModel.startService(context)
                // serviceViewModel.setVPNPermission(true)
                val tk = getPreferenceString(context, PreferenceName.PreferenceToken)?:""
                println("now token value2 = '${tokenvalue}'")
                serviceViewModel.startService(context, allroutes.value.toTypedArray(), tk)
            }
            RESULT_CANCELED -> {
                Toast.makeText(context, "vpn permission denied", Toast.LENGTH_SHORT).show()
            }
        }
    }

    val buttonState = buttonViewModel.buttonState.collectAsState()
    val showTokenDialog = remember { mutableStateOf(false) }



    CustomHeaderScreen(
        "",
        onBack = null,
        onMenu = {
            HomeDropdownMenu(showTokenDialog)
        }
    ) {
        if (showTokenDialog.value) {
            AlertDialog(
                onDismissRequest = {showTokenDialog.value=false},
                confirmButton = {
                    Button(
                        onClick = {
                            setPreferenceString(context, PreferenceName.PreferenceToken, tokenvalue)
                            println("now token value = '${tokenvalue}'")
                            showTokenDialog.value = false
                        }
                    ) {
                        Text("确定")
                    }
                },
                title = {
                    Text("修改token")
                },
                text = {
                    TextField(
                        value = tokenvalue,
                        onValueChange = { newValue ->
                            tokenvalue = newValue.trim()
                        },
                        leadingIcon = {
                            Icon(
                                painter = painterResource(R.drawable.tag),
                                contentDescription = "token",
                                modifier = Modifier.size(24.dp)
                            )
                        },
                    )
                }

            )
        }

        Column(
            modifier = Modifier.fillMaxWidth()
                .padding(top=50.dp),
            horizontalAlignment = Alignment.CenterHorizontally,

            ) {
            Image(
                painter = painterResource(R.drawable.punchnet_log),
                contentDescription = "logo",
                modifier = Modifier.size(150.dp)
            )

            Text(
                "Connecting the Infinite",
                fontSize = 30.sp,
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(top=24.dp)
            )

            Text(
                "Welcome to PunchNet",
                style = MaterialTheme.typography.titleSmall,
                modifier = Modifier.padding(top=8.dp)
            )

            Button(
                onClick = {
                    if (buttonViewModel.buttonState.value == ButtonState.ButtonStarted) {
                    // if (serviceViewModel.isRunning.value) {
                        // if is running, should stop service
                        serviceViewModel.stopVpnService(context)
                    } else if (buttonViewModel.buttonState.value == ButtonState.ButtonStopped){
                        val intent = VpnService.prepare(context)
                        if (intent != null) {
                            vpnLauncher.launch(intent)
                        } else {
                            val tk = getPreferenceString(context, PreferenceName.PreferenceToken)?:""
                            println("now token value1 = '${tokenvalue}'")
                            serviceViewModel.startService(context, allroutes.value.toTypedArray(), tk)
                        }
                    }
                    // started.value = !started.value
                },
                enabled = buttonState.value.enabled,
                shape = RoundedCornerShape(10.dp),
                modifier = Modifier.padding(top=48.dp)
                    .width(120.dp)
                    .height(40.dp)
            ) {
                Text(
                    buttonState.value.text
                    // buttonViewModel.buttonText.value
                    /*
                    if (serviceViewModel.isRunning.value) {
                        "停止"
                    } else {
                        "启动"
                    }
                     */
                )
            }
        }
        // BasicCardList(dbdao = dbdao, navController)
    }
}

