package com.lanyun.wanglaotou.composable


import android.util.Log
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.AppCompatImageView
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.*


import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import com.lanyun.common.baseDate.updateMainEvent
import com.lanyun.common.model.MainEvent
import com.lanyun.wanglaotou.AppConfig
import com.lanyun.wanglaotou.KeyNavigationRoute
import com.lanyun.wanglaotou.dao.AppInfo
import com.lanyun.wanglaotou.public.*
import com.lanyun.wanglaotou.util.MmkvManager
import com.lanyun.wanglaotou.viewModel.MainViewModel
import com.lanyun.wanglaotou.viewModel.PerAppComposeViewModel
import com.lanyun.wanglaotou.viewModel.PerAppViewAction
import kotlinx.coroutines.launch



@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun PerAppCompose(
    navHostController: NavHostController,
    mainViewModel: MainViewModel,
    perAppComposeViewModel: PerAppComposeViewModel = viewModel()
){
    val  viewState = perAppComposeViewModel.viewStates
    val keyboardController = LocalSoftwareKeyboardController.current

    var selectAppProxy by remember {
        mutableStateOf(perAppComposeViewModel.decodeAppProxy())
    }
    var bypassAppProxy by remember {
        mutableStateOf(perAppComposeViewModel.decodeBypassApp())
    }


    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(key1 = Unit) {
        val observer = object : LifecycleObserver {
            @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
            fun onResume() {

            }

            @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
            fun onPause() {
               perAppComposeViewModel.updateProxySet()
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }

    }



    LcePage(pageState = viewState.pageState, onRetry = {
        perAppComposeViewModel.dispatch(PerAppViewAction.AppProxy)
    }) {

        var textFieldValue by remember { mutableStateOf(TextFieldValue("")) }
        BaseScreen {
           Column(modifier = Modifier.fillMaxSize()){

               AppSearchViewBar(
                   textFieldValue= textFieldValue,
                   title = "应用分流",
                   onValueChange = { changeValue ->
                       textFieldValue = changeValue
                       if (changeValue.text.isEmpty()){
                           perAppComposeViewModel.updateData()
                       } else {
                           perAppComposeViewModel.filterProxyApp(textFieldValue.text)
                       }
                   },
                   leftIcon = Icons.Default.ArrowBack,
                   onLeftClick = {
                       navHostController.navigateUp()
                   },
                   rightIcon = Icons.Default.Search,
                   onRightClick = {

                       perAppComposeViewModel.updateData()
                       keyboardController?.hide()
                   })


               SwipeRefreshContent(
                   viewModel = perAppComposeViewModel,
                   listData = viewState.dataList,
                   state = viewState.listState,
                   itemContent = {
                        item {
                            SimpleCard(

                                content = {
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(10.dp),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Row(
                                            modifier = Modifier
                                                .clickable {

                                                selectAppProxy = !selectAppProxy
                                                perAppComposeViewModel.encodeAppProxy(selectAppProxy)

                                            },
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Text(text = "分应用代理")
                                            Spacer(modifier = Modifier.width(15.dp))
                                            Checkbox(
                                                selectAppProxy,
                                                onCheckedChange = null,
                                                modifier = Modifier.size(6.dp),
                                                colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary)
                                            )
                                        }
                                        Spacer(modifier = Modifier.width(20.dp))
                                        Row(
                                            modifier = Modifier.clickable {
                                                bypassAppProxy = !bypassAppProxy
                                                perAppComposeViewModel.encodeBypassApp(bypassAppProxy)
                                            },
                                            verticalAlignment = Alignment.CenterVertically

                                        ) {
                                            Text(text = "绕行模式")
                                            Spacer(modifier = Modifier.width(15.dp))
                                            Checkbox(
                                                bypassAppProxy,
                                                onCheckedChange = null,
                                                modifier = Modifier.size(6.dp),
                                                colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary)
                                            )
                                        }
                                    }
                                }
                            )
                        }
                   },
                   noData = {
                       perAppComposeViewModel.dispatch(PerAppViewAction.AppProxy)
                   },
                   content = { index,data ->

                      // val blacklist = viewState.blacklist.contains(data.packageName)

                       PerAppItemContent(data,data.isSelected == 1, onClick = {
                            Log.e("PerAppItem","inex---${index}---pakName--${data.packageName}---Name---${data.appName}")
                            perAppComposeViewModel.updateSelectIndex(data.packageName,index)
                       }, onCheckedChange = { checked ->

                       })
                   },
                   bottomContent = {

                   }
               )
           }

        }

    }

}

@Composable
fun PerAppItemContent(
    data : AppInfo,
    selected: Boolean,
    onClick: () -> Unit = {},
    onCheckedChange: (Boolean) -> Unit,
){
    Row(
        modifier = Modifier
            .clickable(onClick = onClick)
            .fillMaxSize()
            .padding(top = 6.dp, bottom = 6.dp, start = 5.dp, end = 10.dp),

        verticalAlignment = Alignment.CenterVertically

    ){

       // Image(painterResource(data.appIcon),"content description")
       // val drawable = AppCompatResources.getDrawable(LocalContext.current,data.appIcon)

        Image(
            painter = rememberDrawablePainter(drawable = data.appIcon),
            contentDescription = "content description",
            modifier = Modifier.width(40.dp).height(40.dp)
        )
        // widget.ImageView
//        AndroidView(factory = { ctx ->
//            //  Initialize a View or View hierarchy here
//            AppCompatImageView(ctx).apply {
//                setImageDrawable(data.appIcon)
//            }
//        }, modifier = Modifier
//            .height(40.dp)
//            .width(40.dp))

        Column(

        ) {
            if (data.isSystemApp){
                Text(text = String.format("** %1s",data.appName))
            } else {
                Text(text = data.appName)

            }
            Spacer(modifier = Modifier.height(2.dp))

            Text(text = data.packageName)

        }
        Spacer(modifier = Modifier.weight(1f,true))
        Checkbox(
            selected,
            onCheckedChange = null,
            modifier = Modifier.size(6.dp),
            colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary)
        )
    }

}

