package com.lanyun.wanglaotou.composable

import android.preference.PreferenceManager
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.google.accompanist.insets.navigationBarsHeight
import com.google.accompanist.insets.navigationBarsPadding
import com.google.accompanist.insets.statusBarsHeight
import com.google.accompanist.insets.statusBarsPadding
import com.lanyun.common.baseDate.CommonConstant
import com.lanyun.common.ext.toJsonStr
import com.lanyun.common.widget.SpUtilsMMKV
import com.lanyun.net.widget.DataStoreUtils
import com.lanyun.wanglaotou.AppConfig
import com.lanyun.wanglaotou.KeyNavigationRoute
import com.lanyun.wanglaotou.dao.ERoutingMode
import com.lanyun.wanglaotou.public.*
import com.lanyun.wanglaotou.ui.theme.*
import com.lanyun.wanglaotou.viewModel.SettingsAction
import com.lanyun.wanglaotou.viewModel.SettingsViewModel

@Composable
fun SettingCompose(
    navHostController: NavHostController,
    settingsViewModel: SettingsViewModel = viewModel()
) {
    DisposableEffect(Unit) {

        onDispose {

        }
    }

    var routeMode by remember {
        mutableStateOf(settingsViewModel.getAppRouteMode(AppConfig.PREF_ROUTING_MODE))
    }

    var localDns by remember {
        mutableStateOf(settingsViewModel.getDecodeBool(AppConfig.PREF_LOCAL_DNS_ENABLED))
    }

    var fakeDns by remember {
        mutableStateOf(settingsViewModel.getDecodeBool(AppConfig.PREF_FAKE_DNS_ENABLED))
    }

    var perApp by remember {
        mutableStateOf(settingsViewModel.decodeAppProxySet())
    }

    val localDnsPort by remember {
        mutableStateOf(settingsViewModel.getDecodeString(AppConfig.PORT_LOCAL_DNS))
    }

    val vpnDnsPort by remember {
        mutableStateOf(settingsViewModel.getDecodeString(AppConfig.DNS_AGENT))
    }

    var loginDialog by remember {
        mutableStateOf(false)
    }

    if (loginDialog){
        SimpleAlertDialog(
            "温馨提示",
            "确定退出登录吗",
            confirmStr = "退出",
            confirmClick = {
                //保存登录数据
                SpUtilsMMKV.put(CommonConstant.IS_LOGIN,false)
                //保存信息
                DataStoreUtils.clearSync()
                //DataStoreUtils.putSyncData("auth_data",userLogin.value?.auth_data)
                //保存用户信息
                SpUtilsMMKV.removeKey(CommonConstant.USER_FINO)
                //SpUtilsMMKV.put(CommonConstant.USER_FINO, userLogin.value.toJsonStr())
                navHostController.navigateUp()
        } ){
            loginDialog = false
        }
    }

    if (!settingsViewModel.isLogin()){
        NoLogin(navHostController)
    } else {

        Column(modifier = Modifier
            .fillMaxSize()
            .navigationBarsPadding()
        ) {

            Spacer(
                modifier = Modifier
                    .background(MaterialTheme.colors.background)
                    .statusBarsHeight()
                    .fillMaxWidth()
            )

            AppBar(
                "订阅配置",
                leftIcon = Icons.Default.ArrowBack,
                onLeftClick = {
                    navHostController.navigateUp()
                })

            LazyColumn(modifier = Modifier.fillMaxSize()
            ){
                item {
                    TopText(text = "路由设置")
                    ColumnTextTextScreen("路由",if (routeMode) "全局" else "绕过中国大陆和局域网" , onClick = {
                        routeMode = !routeMode
                        when (routeMode) {
                            //局部
                            true -> settingsViewModel.onAppConfigChanged(AppConfig.PREF_ROUTING_MODE,ERoutingMode.GLOBAL_PROXY.value)
                            //
                            false -> settingsViewModel.onAppConfigChanged(AppConfig.PREF_ROUTING_MODE,ERoutingMode.BYPASS_LAN_MAINLAND.value)
                        }
                    }){
                        Checkbox(
                            routeMode,
                            onCheckedChange = null,
                            modifier = Modifier.size(6.dp),
                            colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary)
                        )
                    }

                    //分割线
                    Spacer(modifier = Modifier
                        .background(colorUnselected)
                        .fillMaxWidth()
                        .height(1.dp)
                        .padding(start = 2.dp, end = 2.dp))

                    TopText(text = "VPN 设置")
                    ColumnTextTextScreen("分应用代理","常规:勾选的App被代理,未勾选的直连;\\n绕行模式:勾选的App直连,未勾选的被代理.\\n不明白者在菜单中选择自动选中需代理应用", onClick = {

                        perApp = !perApp
                        when (perApp) {
                            //开启fake本地dns
                            true -> {
                                settingsViewModel.onAppConfigChanged(AppConfig.PREF_PER_APP_PROXY,true)
                                navHostController.navigate(KeyNavigationRoute.PERAPPPROXY.route)
                            }
                            //关闭fake本地dns
                            false -> {
                            }
                        }

                    }){
                        Checkbox(
                            perApp,
                            onCheckedChange = null,
                            modifier = Modifier.size(6.dp),
                            colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary)
                        )
                    }

                    ColumnTextTextScreen("启本地DNS","DNS 请求导入 core 由 DNS 模块处理（推荐启用 如果需要路由绕过局域网及大陆地址)", onClick = {
                        localDns = !localDns
                        when (localDns) {
                            //开启本地dns
                            true -> settingsViewModel.onAppConfigChanged(AppConfig.PREF_LOCAL_DNS_ENABLED,localDns)
                            //关闭本地dns
                            false -> settingsViewModel.onAppConfigChanged(AppConfig.PREF_LOCAL_DNS_ENABLED,localDns)
                        }
                    }){
                        Checkbox(
                            localDns,
                            onCheckedChange = null,
                            modifier = Modifier.size(6.dp),
                            colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary)
                        )
                    }

                    ColumnTextTextScreen("启用虚拟DNS","本地返回虚构解析结果 (减低延时 但个别应用可能无法使用)", isDisallow = !localDns, onClick = {
                        if(!localDns){
                            return@ColumnTextTextScreen
                        }

                        fakeDns = !fakeDns
                        when (fakeDns) {
                            //开启fake本地dns
                            true -> {
                                settingsViewModel.onAppConfigChanged(AppConfig.PREF_LOCAL_DNS_ENABLED,fakeDns)
                                localDns = fakeDns
                            }
                            //关闭fake本地dns
                            false -> settingsViewModel.onAppConfigChanged(AppConfig.PREF_LOCAL_DNS_ENABLED,fakeDns)
                        }

                    }){
                        Checkbox(
                            fakeDns,
                            onCheckedChange = null,
                            modifier = Modifier.size(6.dp),
                            colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary)
                        )
                    }



                    ColumnTextTextScreen(topStr = "VPN DNS (仅支持 IPv4/v6)", bottomStr = vpnDnsPort.ifEmpty { AppConfig.DNS_AGENT }, isDisallow = !localDns){

                    }
                    ColumnTextTextScreen(topStr = "本地DNS端口", bottomStr = localDnsPort.ifEmpty { AppConfig.PORT_LOCAL_DNS },isDisallow = !localDns){

                    }



                    //分割线
                    Spacer(modifier = Modifier
                        .background(colorUnselected)
                        .fillMaxWidth()
                        .height(1.dp)
                        .padding(start = 2.dp, end = 2.dp))

                    TopText(text = "用户")
                    ColumnTextTextScreen("订单", bottomStr = "我的订单", onClick = {
                        navHostController.navigate("${KeyNavigationRoute.WEBVIEW.route}?url=/order&title=我的订单")
                    })
                    ColumnTextTextScreen("工单", bottomStr = "我的工单", onClick = {
                        navHostController.navigate("${KeyNavigationRoute.WEBVIEW.route}?url=/ticket&title=我的工单")
                    })

                    ColumnTextTextScreen("邀请", bottomStr = "我的邀请", onClick = {
                        navHostController.navigate("${KeyNavigationRoute.WEBVIEW.route}?url=/invite&title=我的邀请")
                    })

                    ColumnTextTextScreen("个人", bottomStr = "个人中心", onClick = {
                        navHostController.navigate("${KeyNavigationRoute.WEBVIEW.route}?url=/profile&title=个人中心")
                    })

                    ColumnTextTextScreen("流量", bottomStr = "流量明细", onClick = {
                        navHostController.navigate("${KeyNavigationRoute.WEBVIEW.route}?url=/traffic&title=流量明细")
                    })

                    ColumnTextTextScreen("教程", bottomStr = "教程说明", onClick = {
                        navHostController.navigate("${KeyNavigationRoute.WEBVIEW.route}?url=/knowledge&title=教程说明")
                    })

                    ColumnTextTextScreen("用户退出", bottomStr = "", onClick = {
                        loginDialog = true
                    })

                }
            }

            Spacer(
                modifier = Modifier
                    .background(MaterialTheme.colors.background)
                    .navigationBarsHeight()
                    .fillMaxWidth()
            )
        }
    }



}


/**
 * 列表第一个Text 主题颜色
 */
@Composable
private fun TopText(text: String) {
    Text(
        text,
        fontSize = 14.sp,
        color = MaterialTheme.colors.primary,
        modifier = Modifier.padding(start = 20.dp, top = 13.dp, bottom = 13.dp)
    )
}
/**
 * 上下文字列表的布局
 */
@Composable
private fun ColumnTextTextScreen(
    topStr: String,
    bottomStr: String,
    paddingTop: Dp = 13.dp,
    paddingBottom: Dp = 13.dp,
    isDisallow:Boolean = false,
    onClick: () -> Unit = {},
    context: @Composable () -> Unit = {},
) {
    ColumnTextText(
        topStr,
        bottomStr,
        modifier = Modifier
            .clickable(onClick = onClick)
            .background(if (isDisallow) grey2 else white)
            .padding(top = paddingTop, bottom = paddingBottom, start = 20.dp, end = 20.dp),
        context = context
    )
}