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.Arrangement
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.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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.text.style.TextAlign
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.NavHostController
import androidx.navigation.compose.rememberNavController
import com.img.rabbit.R
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.AccountBindViewModel
import com.img.rabbit.viewmodel.BindViewModel
import com.img.rabbit.viewmodel.LoginViewModel

@SuppressLint("UnrememberedMutableState")
@Composable
fun AccountBindScreen(navController: NavHostController, viewModel: AccountBindViewModel = viewModel(), loginViewModel: LoginViewModel) {
    val context = LocalContext.current
    /**
    * 0:m默认未绑定，1:已绑定手机号（去解绑），2:已绑定微信（去解绑）
     */
    val showDialogStatus = mutableIntStateOf(0)
    val userInfo by remember { mutableStateOf(PreferenceUtil.getUserInfo()) }


    LaunchedEffect(viewModel.unBindState.value) {
        if(viewModel.unBindState.value != null){
            // 获取用户配置
            loginViewModel.requestUserConfig()
            // 获取用户信息
            loginViewModel.requestUserInfo()

            Toast.makeText(context, "解绑成功!", Toast.LENGTH_SHORT).show()
            viewModel.unBindState.value = null
            GlobalStateManager(context).storeGlobalUnBindNotify(true)
            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()
        ){
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                TitleBar(navController = navController, paddingValues = it, title = "账号绑定")

                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(start = 17.dp, end = 17.dp)
                ){
                    // 设置内容
                    Column(
                        modifier = Modifier
                            .wrapContentSize()
                            .padding(top = 16.dp)
                            .background(
                                Color(0xFFFFFFFF),
                                RoundedCornerShape(18.dp)
                            )
                            .shadow(
                                elevation = 4.dp,
                                shape = RoundedCornerShape(8.dp),
                                ambientColor = Color(0x4DE5E5E5),
                                spotColor = Color(0x4DE5E5E5)
                            )
                    ){
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(52.dp)
                                .clickable(
                                    indication = null,
                                    interactionSource = remember { MutableInteractionSource() }
                                ) {
                                    // 跳转绑定与解绑手机号
                                    if (userInfo?.phone.isNullOrEmpty()) {
                                        navController.navigate("bind?type=${BindViewModel.BindType.FROM_PHONE.type}")
                                    } else {
                                        showDialogStatus.intValue = 1
                                    }
                                },
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Box(
                                modifier = Modifier.weight(1f)
                            ){
                                Text(
                                    text = "手机号",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = Color(0xFF1A1A1A),
                                    modifier = Modifier
                                        .wrapContentSize()
                                        .padding(start = 8.dp)
                                )
                            }

                            Row(
                                modifier = Modifier.wrapContentSize()
                            ) {
                                val phone = if(userInfo?.phone.isNullOrEmpty()){
                                    "去绑定"
                                }else{
                                    "+86 ${userInfo?.phone?.replaceRange(3, 7, "****") ?: ""}"
                                }

                                Text(
                                    phone,
                                    fontSize = 16.sp,
                                    fontWeight = FontWeight.Normal,
                                    modifier = Modifier
                                        .wrapContentSize()
                                        .align(Alignment.CenterVertically),
                                    color = Color(0xFF767676),
                                    textAlign = TextAlign.Center
                                )
                                Image(
                                    painter = painterResource(id = R.mipmap.ic_arrow_right),
                                    contentDescription = null,
                                    contentScale = ContentScale.FillWidth,
                                    modifier = Modifier
                                        .wrapContentSize()
                                        .padding(end = 12.dp)
                                        .align(Alignment.CenterVertically)
                                )
                            }
                        }
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(0.5.dp)
                                .padding(horizontal = 12.dp)
                                .background(
                                    Color(0x4DBBBBBB)
                                )
                        )
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(52.dp)
                                .clickable(
                                    indication = null,
                                    interactionSource = remember { MutableInteractionSource() }
                                ) {
                                    //TODO 跳转绑定或解绑微信
                                    if (userInfo?.weixinAppId.isNullOrEmpty()) {
                                        navController.navigate("bind?type=${BindViewModel.BindType.FROM_WX.type}")
                                    } else {
                                        showDialogStatus.intValue = 2
                                    }
                                },
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Box(
                                modifier = Modifier.weight(1f)
                            ){
                                Text(
                                    text = "微信账号",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = Color(0xFF1A1A1A),
                                    modifier = Modifier
                                        .wrapContentSize()
                                        .padding(start = 8.dp)
                                )
                            }

                            Row(
                                modifier = Modifier.wrapContentSize()
                            ) {
                                val wxBind = if(userInfo?.weixinAppId.isNullOrEmpty()){
                                    "去绑定"
                                }else{
                                    "已绑定，去解绑"
                                }
                                Text(
                                    wxBind,
                                    fontSize = 16.sp,
                                    fontWeight = FontWeight.Normal,
                                    modifier = Modifier
                                        .wrapContentSize()
                                        .align(Alignment.CenterVertically),
                                    color = Color(0xFF767676),
                                    textAlign = TextAlign.Center
                                )
                                Image(
                                    painter = painterResource(id = R.mipmap.ic_arrow_right),
                                    contentDescription = null,
                                    contentScale = ContentScale.FillWidth,
                                    modifier = Modifier
                                        .wrapContentSize()
                                        .padding(end = 12.dp)
                                        .align(Alignment.CenterVertically)
                                )
                            }
                        }
                    }
                }
            }

            if(showDialogStatus.intValue > 0){
                UnBindPhoneDialog(
                    showDialogStatus = showDialogStatus,
                    onStatusChange = { stateVal, typeVal, isCancel ->
                        if(!isCancel){
                            if(typeVal == 1){
                                // 解绑手机号
                                PreferenceUtil.getUserInfo()?.phone?.let { phone -> viewModel.requestUnBindByPhone(phone) }
                            }else{
                                // 解绑微信
                                PreferenceUtil.getWxCode()?.let { wechatCode -> viewModel.requestUnBindByWechat(wechatCode) }
                            }
                        }

                        showDialogStatus.intValue = stateVal
                    }
                )
            }
        }
    }
}

@Composable
private fun UnBindPhoneDialog(
    showDialogStatus: MutableState<Int>,
    onStatusChange: (state:Int, type:Int, isCancel:Boolean) -> Unit
){
    val title = if(showDialogStatus.value == 1){
        "解开绑定的手机号？"
    }else{
        "确定解除绑定的微信？"
    }
    val content = if(showDialogStatus.value == 1){
        "当前绑定的手机号码为"
    }else{
        "解除后将无法使用该微信登录此账号，请谨慎操作！"
    }
    val content1 = if(showDialogStatus.value == 1){
        "+86 ${PreferenceUtil.getUserInfo()?.phone?.replaceRange(3, 7, "****") ?: ""}"
    }else{
        ""
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0x80000000))
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() }
            ) {
                onStatusChange(0, showDialogStatus.value, true)
            },
        verticalArrangement = Arrangement.Center
    ){
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
                .padding(horizontal = 36.dp)
                .background(Color.White, shape = RoundedCornerShape(26.dp))
                .align(Alignment.CenterHorizontally)
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }
                ) {
                    //什么都不用做，只是解决点击穿透问题
                }
        ) {
            Image(
                painter = painterResource(id = R.mipmap.ic_dialog_top_mask1),
                contentDescription = null,
                contentScale = ContentScale.FillWidth,
                modifier = Modifier
                    .fillMaxWidth()
            )

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .padding(top = 46.dp)
            ) {
                Text(
                    text = title,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1A1A1A),
                    modifier = Modifier
                        .wrapContentSize()
                        .align(Alignment.CenterHorizontally)
                )

                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(14.dp)
                )

                Text(
                    text = content,
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color(0xFF767676),
                    modifier = Modifier
                        .wrapContentSize()
                        .align(Alignment.CenterHorizontally)
                )

                Text(
                    text = content1,
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color(0xFF767676),
                    modifier = Modifier
                        .wrapContentSize()
                        .align(Alignment.CenterHorizontally)
                )


                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(16.dp)
                )

                //切换/退出账号
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 18.dp, end = 18.dp, bottom = 20.dp)
                ) {
                    //取消解绑手机号
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentHeight()
                            .weight(1f)
                            .background(
                                Color(0x00000000),
                                shape = RoundedCornerShape(359.dp),
                            )
                            .border(
                                width = 1.dp,
                                color = Color(0xFF000000),
                                shape = RoundedCornerShape(359.dp)
                            )
                            .clickable(
                                indication = null,
                                interactionSource = remember { MutableInteractionSource() }
                            ) {
                                // 取消解绑手机号
                                onStatusChange(0, showDialogStatus.value, true)
                            }
                    ) {
                        Text(
                            "取消",
                            color = Color(0xFF1A1A1A),
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier
                                .wrapContentWidth()
                                .wrapContentHeight()
                                .padding(vertical = 12.dp)
                                .align(Alignment.Center)
                        )
                    }

                    Box(
                        modifier = Modifier
                            .width(11.dp)
                    )



                    //退出登录
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentHeight()
                            .weight(1f)
                            .background(
                                Color(0xFF252525),
                                shape = RoundedCornerShape(359.dp),
                            )
                            .clickable(
                                indication = null,
                                interactionSource = remember { MutableInteractionSource() }
                            ) {
                                //TODO 确定解绑手机号
                                onStatusChange(0, showDialogStatus.value, false)
                            }
                    ) {
                        Text(
                            "确定",
                            color = Color(0xFFC2FF43),
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier
                                .wrapContentWidth()
                                .wrapContentHeight()
                                .padding(vertical = 12.dp)
                                .align(Alignment.Center)
                        )
                    }
                }
            }

        }
    }
}

@Preview(showBackground = true)
@Composable
private fun PreviewAccountBindScreen(){
    AccountBindScreen(navController = rememberNavController(), loginViewModel = LoginViewModel())
}

@SuppressLint("UnrememberedMutableState")
@Preview(showBackground = true)
@Composable
private fun PreviewUnBindPhoneDialog(){
    UnBindPhoneDialog(showDialogStatus = mutableIntStateOf(0), onStatusChange = { _, _, _->})
}
