package com.img.rabbit.pages.screen.mine.setting

import android.annotation.SuppressLint
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
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.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import coil3.compose.AsyncImage
import com.img.rabbit.R
import com.img.rabbit.bean.response.UserInfoEntity
import com.img.rabbit.pages.dialog.TipsDialog
import com.img.rabbit.pages.toolbar.TitleBar
import com.img.rabbit.provider.storage.GlobalStateManager
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.viewmodel.AccountManagerViewModel
import com.img.rabbit.viewmodel.LoginViewModel

@SuppressLint("UnrememberedMutableState")
@Composable
fun AccountManagerScreen(navController: NavHostController, viewModel: AccountManagerViewModel = viewModel(), loginViewModel: LoginViewModel) {
    val context = LocalContext.current
    var globalLogin by mutableStateOf(GlobalStateManager(context).globalLoginNotifyFlow().collectAsState(initial = false))
    var showDialogStatus by mutableStateOf(false)
    var selectedUserInfo by mutableStateOf<UserInfoEntity?>(null)

    val userList by remember { viewModel.accountState }

    LaunchedEffect(Unit) {
        viewModel.requestAccount()
    }

    if(globalLogin.value == true){
        viewModel.requestAccount()
    }

    LaunchedEffect(viewModel.switchState.value) {
        if (viewModel.switchState.value != null && viewModel.switchState.value?.data?.token != null) {
            // 切换账号成功
            PreferenceUtil.saveAccessToken(viewModel.switchState.value?.data?.token)
            // 获取用户配置
            loginViewModel.requestUserConfig()
            // 获取用户信息
            loginViewModel.requestUserInfo()

            loginViewModel.setLogin(true)
            //更新登录状态
            GlobalStateManager(context).storeGlobalLoginNotify(true)
            //清理loginState
            loginViewModel.loginState.value = null
            Toast.makeText(context, "切换账号成功！", Toast.LENGTH_SHORT).show()

            navController.popBackStack()
        }
    }
    LaunchedEffect(viewModel.errorState.value) {
        if(viewModel.errorState.value != null){
            Toast.makeText(context, "切换账号失败...", Toast.LENGTH_SHORT).show()
            viewModel.errorState.value = null
        }
    }

    Scaffold{
        Box(
            modifier = Modifier.fillMaxSize()
        ){
            Image(
                painter = painterResource(id = R.mipmap.ic_account_switch_top_mask),
                contentDescription = "蒙层",
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )


            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                TitleBar(navController = navController, paddingValues = it, title = "")

                Column(
                    modifier = Modifier.fillMaxWidth().padding(top = 100.dp)
                ) {

                    Text(
                        text = "轻触头像以切换帐号",
                        color = Color(0xFF3D3D3D),
                        fontSize = 24.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.align(Alignment.CenterHorizontally)
                    )
                }

                Box(
                    modifier = Modifier.fillMaxSize().padding(top = 55.dp, start = 17.dp, end = 17.dp)
                ){
                    // 设置内容
                    LazyColumn {
                        // 添加五个项目
                        items(userList?.size ?: 0) { index ->
                            userList?.get(index)?.let {userInfoEntity ->
                                ListItem(userInfoEntity){
                                    showDialogStatus = true
                                    selectedUserInfo = userInfoEntity
                                }
                            }
                        }
                        item {
                            AddItem(navController)
                        }
                    }
                }
            }
            if(showDialogStatus){
                TipsDialog(
                    title = "您确定要切换账户吗？",
                    content1 = "",
                    content2 = null,
                    cancel = "取消",
                    confirm = "确定",
                    data = selectedUserInfo,
                    onStatusChange = { status, isCancel, data ->
                        if(!isCancel && data != null){
                            // 切换账号
                            viewModel.switchAccount((data as UserInfoEntity).user_id)
                        }
                        showDialogStatus = status
                    }
                )
            }
        }
    }


}

@Composable
private fun ListItem(item: UserInfoEntity, onChange: (UserInfoEntity) -> Unit){
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
            .padding(bottom = 10.dp)
            .background(
                color = Color(0xFFFFFFFF),
                shape = RoundedCornerShape(8.dp)
            )
            .shadow(
                elevation = 4.dp,
                shape = RoundedCornerShape(8.dp),
                ambientColor = Color(0x4DE5E5E5),
                spotColor = Color(0x4DE5E5E5)
            )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 11.dp, vertical = 17.dp)
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }
                ) {
                    // 切换账号
                    onChange(item)
                },
            verticalAlignment = Alignment.CenterVertically
        ) {
            AsyncImage(
                model = item.avater,
                contentDescription = "用户头像",
                contentScale = ContentScale.FillWidth,
                modifier = Modifier
                    .size(46.dp)
                    .align(Alignment.CenterVertically)
                    .clip(RoundedCornerShape(8.dp)),
                fallback = painterResource(id = R.mipmap.ic_launcher_logo),
                error = painterResource(id = R.mipmap.ic_launcher_logo)
            )

            Column(
                modifier = Modifier.weight(1f)
            ){
                Text(
                    text = item.name,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1A1A1A),
                    modifier = Modifier
                        .wrapContentSize()
                        .padding(start = 8.dp)
                )
                Text(
                    text = "ID:${item.user_id}",
                    fontSize = 12.sp,
                    color = Color(0xFF767676),
                    fontWeight = FontWeight.Normal,
                    modifier = Modifier
                        .wrapContentSize()
                        .padding(start = 8.dp)
                )
            }


            Row(
                modifier = Modifier.wrapContentSize()
            ) {
                val isLogin = PreferenceUtil.getUserInfo()?.user_id == item.user_id
                Checkbox(
                    checked = isLogin,
                    onCheckedChange = { isChecked ->
                        //viewModel.setIsPolicyAgreement(isChecked)
                    },
                    modifier = Modifier
                        .size(16.dp)
                        .scale(0.35f)
                        .padding(start = 6.dp)
                        .background(
                            if (isLogin) Color(0xFF252525)
                            else Color.Transparent,
                            shape = RoundedCornerShape(36.dp)
                        )
                        .border(
                            width = 1.dp,
                            color = if (isLogin) Color(0xFF252525)
                            else Color(0xFFCCCCCC),
                            shape = RoundedCornerShape(36.dp)
                        )
                        .align(Alignment.CenterVertically),
                    colors = androidx.compose.material3.CheckboxDefaults.colors(
                        checkedColor = Color.Transparent,    // 隐藏默认背景
                        uncheckedColor = Color.Transparent,  // 隐藏默认背景
                        checkmarkColor = Color.White
                    )

                )
            }
        }
    }
}


@Composable
private fun AddItem(navController: NavController){
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
            .padding(bottom = 16.dp)
            .background(
                color = Color(0xFFFFFFFF),
                shape = RoundedCornerShape(8.dp)
            )
            .shadow(
                elevation = 4.dp,
                shape = RoundedCornerShape(8.dp),
                ambientColor = Color(0x4DE5E5E5),
                spotColor = Color(0x4DE5E5E5)
            )
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() }
            ) {
                //TODO 添加账号
                navController.navigate("login?type=${LoginViewModel.JumpLoginType.FROM_ADD.type}")
            }
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 11.dp, vertical = 17.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(id = R.mipmap.ic_picture_add),
                contentDescription = null,
                contentScale = ContentScale.FillWidth,
                modifier = Modifier
                    .size(46.dp)
                    .align(Alignment.CenterVertically)
                    .background(Color(0xFFF3F3F3), shape = RoundedCornerShape(8.dp))
                    .clip(RoundedCornerShape(8.dp))
            )

            Column(
                modifier = Modifier.weight(1f)
            ){
                Text(
                    text = "添加账号",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1A1A1A),
                    modifier = Modifier
                        .wrapContentSize()
                        .padding(start = 8.dp)
                )
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun PreviewAccountManagerScreen(){
    AccountManagerScreen(navController = rememberNavController(), loginViewModel = viewModel())
}