package com.img.rabbit.pages.screen

import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.height
import androidx.compose.foundation.layout.offset
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.shape.RoundedCornerShape
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.rememberCoroutineScope
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.shadow
import androidx.compose.ui.graphics.Brush
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.TextStyle
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.NavHostController
import androidx.navigation.compose.rememberNavController
import coil3.compose.AsyncImage
import com.img.rabbit.BuildConfig
import com.img.rabbit.R
import com.img.rabbit.provider.storage.GlobalStateManager
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.utils.AppUpdate
import com.img.rabbit.viewmodel.GeneralViewModel
import com.img.rabbit.viewmodel.LoginViewModel
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@SuppressLint("UnrememberedMutableState", "CoroutineCreationDuringComposition")
@Composable
fun MineScreen(
    navController: NavHostController,
    generalViewModel: GeneralViewModel,
) {
    val TAG = "Rabbit_Mine"
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var globalLogin by mutableStateOf(GlobalStateManager(context).globalLoginNotifyFlow().collectAsState(initial = false))
    var globalUnBind by mutableStateOf(GlobalStateManager(context).globalUnBindNotifyFlow().collectAsState(initial = false))

    val vipMember by remember { mutableStateOf(false) }
    var userInfo by remember { mutableStateOf(PreferenceUtil.getUserInfo()) }

    // 监听返回事件
    val currentBackStackEntry = navController.currentBackStackEntry

    LaunchedEffect(currentBackStackEntry) {
        // 当返回到MineScreen页面时执行的操作
        if (currentBackStackEntry?.destination?.route == "mine") {
            // 显示TabBar
            generalViewModel.setNavigationBarVisible(true)
        }
    }

    //刷新用户信息
    if(globalLogin.value == true || globalUnBind.value == true){
        scope.launch {
            delay(300)
            userInfo = PreferenceUtil.getUserInfo()
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFF9F9F9))
    ){
        Image(
            painter = painterResource(id = R.mipmap.ic_mine_top_mask),
            contentDescription = null,
            contentScale = ContentScale.FillWidth,
            modifier = Modifier.fillMaxWidth()
        )
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(start = 16.dp, end = 16.dp, top = 112.dp)
        ) {
            // 头像和登录/注册
            Row(
                modifier = Modifier.fillMaxWidth()
            ) {
                if(userInfo == null){
                    Image(
                        painter = painterResource(id = R.mipmap.ic_user_avatar_default),
                        contentDescription = "用户头像",
                        contentScale = ContentScale.FillWidth,
                        modifier = Modifier
                            .size(64.dp)
                            .clip(RoundedCornerShape(90.dp))
                            .clickable(
                                indication = null,
                                interactionSource = remember { MutableInteractionSource() }
                            ) {
                                // 处理点击事件
                                Toast.makeText(context, "头像", Toast.LENGTH_SHORT).show()
                            }
                    )
                }else{
                    AsyncImage(
                        model = userInfo?.avater,
                        contentDescription = "用户头像",
                        contentScale = ContentScale.FillWidth,
                        modifier = Modifier
                            .size(64.dp)
                            .clip(RoundedCornerShape(90.dp))
                            .clickable(
                                indication = null,
                                interactionSource = remember { MutableInteractionSource() }
                            ) {
                                // 处理点击事件
                                Toast.makeText(context, "头像", Toast.LENGTH_SHORT).show()
                            },
                        fallback = painterResource(id = R.mipmap.ic_user_avatar_default),
                        error = painterResource(id = R.mipmap.ic_user_avatar_default)
                    )
                }
                Column(
                    modifier = Modifier
                        .padding(start = 16.dp)
                        .align(Alignment.CenterVertically)
                        .clickable(
                            indication = null,
                            interactionSource = remember { MutableInteractionSource() }
                        ) {
                            if (userInfo == null) {
                                // 隐藏TabBar
                                generalViewModel.setNavigationBarVisible(false)
                                // 跳转登录页面
                                navController.navigate("login?type=${LoginViewModel.JumpLoginType.NORMAL.type}")
                            } else {
                                //TODO 已登录，跳转个人信息页面
                                //navController.navigate("userInfo")
                            }
                        }
                ) {
                    Text(
                        text = if(userInfo == null){ "登录/注册" }else{ userInfo?.name?:"" },
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1A1A1A),
                        modifier = Modifier.wrapContentSize()
                    )
                    Row(
                        modifier = Modifier
                            .padding(top = 10.dp)
                            .clickable(
                                indication = null,
                                interactionSource = remember { MutableInteractionSource() }
                            ) {
                                // 点击复制ID
                                if (userInfo != null) {
                                    val clipboardManager = android.content.Context.CLIPBOARD_SERVICE
                                    val clipboard =
                                        context.getSystemService(clipboardManager) as android.content.ClipboardManager
                                    val clip = android.content.ClipData.newPlainText(
                                        "User ID",
                                        userInfo?.user_id
                                    )
                                    clipboard.setPrimaryClip(clip)
                                    Toast.makeText(context, "已复制到剪贴板", Toast.LENGTH_SHORT)
                                        .show()
                                }
                            }
                    ){
                        Text(
                            text = if(userInfo == null){ "登录体验更多功能哦~" }else{ "ID:${userInfo?.user_id?:""}" },
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF767676),
                            modifier = Modifier
                                .wrapContentSize()
                        )
                        Box(
                            modifier = Modifier
                                .size(4.dp)
                        )
                        Image(
                            painter = painterResource(id = R.mipmap.ic_copy),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier
                                .size(12.dp)
                                .align(Alignment.CenterVertically)
                        )
                    }
                }
            }

            // VIP bar
            Column(
                modifier = Modifier.fillMaxWidth()
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()
                        .padding(top = 33.dp)
                ){

                    if(vipMember){
                        Image(
                            painter = painterResource(id = R.mipmap.ic_mine_vip_bar_bg1),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier.fillMaxWidth()
                        )
                    }else{
                        Image(
                            painter = painterResource(id = R.mipmap.ic_mine_vip_bar_bg),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier.fillMaxWidth()
                        )
                    }

                    Row(
                        modifier = Modifier.wrapContentSize()
                    ) {
                        Text(
                            text = if (vipMember) "月度会员" else "开通会员",
                            style = TextStyle(
                                brush = Brush.linearGradient(
                                    colors = listOf(Color(0xFFC8FF54), Color(0xFFFFFFFF))
                                ),
                                fontSize = 18.sp,
                                fontWeight = FontWeight.Bold
                            ),
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(start = 14.dp, top = 10.dp)
                        )
                        Text(
                            text = if (vipMember) "2025.12.22前会员到期" else "解锁微圈相册全部特权",
                            fontSize = 12.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color(0xFFFFFFFF),
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(start = 14.dp, top = 10.dp)
                                .align(Alignment.CenterVertically)
                        )
                    }
                }

                if (!vipMember){
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(end = 17.dp)
                            .offset(y = (-40).dp)
                    ) {

                        Image(
                            painter = painterResource(id = R.mipmap.ic_mine_open),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier
                                .wrapContentSize()
                                .align(Alignment.End)
                                .clickable(
                                    indication = null,
                                    interactionSource = remember { MutableInteractionSource() }
                                ) {
                                    // 处理点击事件
                                    Toast.makeText(context, "开通会员", Toast.LENGTH_SHORT).show()
                                }
                        )
                    }
                }

                //功能项
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()
                        .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() }
                            ) {
                                // 隐藏TabBar
                                generalViewModel.setNavigationBarVisible(false)
                                // 跳转反馈页面
                                navController.navigate("feedback")
                            },
                            verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(id = R.mipmap.ic_mine_feedback),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(start = 12.dp)
                        )
                        Box(
                            modifier = Modifier.weight(1f)
                        ){
                            Text(
                                text = "意见反馈",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color(0xFF1A1A1A),
                                modifier = Modifier
                                    .wrapContentSize()
                                    .padding(start = 8.dp)
                            )
                        }

                        Image(
                            painter = painterResource(id = R.mipmap.ic_arrow_right),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(end = 12.dp) // 改为end padding
                        )
                    }
                    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() }
                            ) {
                                // 隐藏TabBar
                                generalViewModel.setNavigationBarVisible(false)
                                // 跳转在线客服页面
                                navController.navigate("onlineService")
                            },
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(id = R.mipmap.ic_mine_service),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(start = 12.dp)
                        )
                        Box(
                            modifier = Modifier.weight(1f)
                        ){
                            Text(
                                text = "在线客服",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color(0xFF1A1A1A),
                                modifier = Modifier
                                    .wrapContentSize()
                                    .padding(start = 8.dp)
                            )
                        }

                        Image(
                            painter = painterResource(id = R.mipmap.ic_arrow_right),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(end = 12.dp) // 改为end padding
                        )
                    }
                    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() }
                            ) {
                                //更新检测
                                val versionConfig =
                                    PreferenceUtil.getUserConfig()?.config?.versionEntity

                                AppUpdate.checkUpdate(versionConfig) { isUpdate, tips ->
                                    if (isUpdate) {
                                        //提示执行更新
                                        //startUpdate(result, fragment)
                                        Log.i(TAG, "checkUpdate: 有新版本, tips = $tips")
                                    } else {
                                        Toast.makeText(context, tips, Toast.LENGTH_SHORT).show()
                                    }
                                }
                            },
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(id = R.mipmap.ic_mine_update),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(start = 12.dp)
                        )
                        Box(
                            modifier = Modifier.weight(1f)
                        ){
                            Text(
                                text = "版本更新",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color(0xFF1A1A1A),
                                modifier = Modifier
                                    .wrapContentSize()
                                    .padding(start = 8.dp)
                            )
                        }

                        Row {
                            Text(
                                text = "V${BuildConfig.VERSION_NAME}",
                                fontSize = 12.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color(0xFFAAAAAA),
                                modifier = Modifier
                                    .wrapContentSize()
                                    .padding(start = 8.dp)
                                    .align(Alignment.CenterVertically)
                            )
                            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() }
                            ) {
                                // 隐藏TabBar
                                generalViewModel.setNavigationBarVisible(false)
                                // 跳转设置页面
                                navController.navigate("setting")
                            },
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(id = R.mipmap.ic_mine_setting),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(start = 12.dp)
                        )
                        Box(
                            modifier = Modifier.weight(1f)
                        ){
                            Text(
                                text = "设置",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color(0xFF1A1A1A),
                                modifier = Modifier
                                    .wrapContentSize()
                                    .padding(start = 8.dp)
                            )
                        }

                        Image(
                            painter = painterResource(id = R.mipmap.ic_arrow_right),
                            contentDescription = null,
                            contentScale = ContentScale.FillWidth,
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(end = 12.dp) // 改为end padding
                        )
                    }
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun PreviewMineScreen(){
    MineScreen(navController = rememberNavController(), generalViewModel = viewModel())
}